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

Nis*_*arg 2 python list remove-method python-3.x

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

所以我从用户那里得到了输入

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

但它给了我一个 ValueError

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

Iva*_*dov 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")
Run Code Online (Sandbox Code Playgroud)

请不要使用list作为变量名,因为它list是一个函数和一个数据类型.