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

时间:2018-04-24 16:44:14

标签: python python-3.x list remove-method

我在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,它适用于整数,但不适用于字符串。

2 个答案:

答案 0 :(得分:6)

它会向您显示错误,因为您要删除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是一个函数和数据类型。

答案 1 :(得分:0)

也可以使用'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]

相关问题