简体   繁体   English

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

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

I am doing a menu driven program in python to insert and delete items in a list. 我正在用python做菜单驱动程序,以插入和删除列表中的项目。 I have a list containing integers and strings. 我有一个包含整数和字符串的列表。 I want to delete integer. 我想删除整数。

So I take input from user as 所以我将用户的输入作为

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

But it gives me a ValueError 但这给我一个ValueError

I typecasted the input to int and it worked for integers but not for the string. 我将输入类型转换为int,它适用于整数,但不适用于字符串。

It gives you an error because you want to remove int , but your input is str . 因为要删除int而给您一个错误,但是您输入的是str Your code will work only if input is 'hi' . 仅当输入为'hi'您的代码才有效。

Try this: 尝试这个:

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")

And please don't use list as a variable name, because list is a function and a data type. 并且请不要将list用作变量名,因为list是函数和数据类型。

Works with 'hi' as input too. 也可以使用'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] [1、2、3、5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM