如何通过从用户输入中删除哪个值来从列表(整数和字符串)中删除整数?

How can I delete integers from list (of integers and strings) by taking which value to delete from user input?

我正在 python 中做一个菜单驱动的程序来插入和删除列表中的项目。我有一个包含整数和字符串的列表。我想删除整数。

所以我接受用户的输入

list = [1, 2, 3, "hi", 5]
x = input("enter the value to be deleted")
# input is given as 2 
list.remove(x)

但它给了我 ValueError

我将输入类型转换为 int,它适用于整数但不适用于字符串。

它给你一个错误,因为你想删除 int,但你的输入是 str。仅当输入为 'hi'.

时,您的代码才有效

试试这个:

arr = [1, 2, 3, "hi", 5]
x = input("enter the value to be deleted")  # x is a str!

if x.isdigit():  # check if x can be converted to int
    x = int(x)  

arr.remove(x)  # remove int OR str if input is not supposed to be an int ("hi")

并且请不要使用list作为变量名,因为list是函数和数据类型。

也可以使用 'hi' 作为输入。

list = [1, 2, 3, "hi", 5]


by_index = input('Do you want to delete an index: yes/no ')
bool_index = False
x = input("enter the value/index to be deleted ")


if by_index.lower() == 'yes':
    del(list[int(x)])

elif by_index.lower() == 'no':
    if x.isdigit():
        x = int(x)
    del(list[list.index(x)])

else:
    print('Error!')


print(list)

[1, 2, 3, 5]