我在 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 ,它适用于整数,但不适用于字符串。
我在 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
是函数和数据类型。
也可用作'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]