我正在用 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
是一个函数,也是一种数据类型。
关于python - 如何通过从用户输入中删除哪个值来从列表(整数和字符串)中删除整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006951/