Python 如果输入是列表的一部分
我被这部分代码卡住了。下面是一个示例文本Python 如果输入是列表的一部分,python,list,python-3.x,Python,List,Python 3.x,我被这部分代码卡住了。下面是一个示例文本 items = [variable1, variable2, variable3] choice = input("Input variable here: ") if choice != items: print("Item not found") else: print("Item found") 这就是我想做的一个例子。我想知道用户输入的内容是否是给定列表的一部分。这是Python3.5,它将取决于列表中的数据类型input将所有
items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if choice != items:
print("Item not found")
else:
print("Item found")
这就是我想做的一个例子。我想知道用户输入的内容是否是给定列表的一部分。这是Python3.5,它将取决于列表中的数据类型
input
将所有内容返回为str
。因此,如果列表数据类型为float
,则if语句的计算结果将为True
。对于int
数据,请使用以下内容:
items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if int(choice) not in items:
print("Item not found")
else:
print("Item found")
对于float
is,必须:
items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if float(choice) not in items:
print("Item not found")
else:
print("Item found")
现在应该正确计算if语句。应该是
if选项不在items
中。如果items
很大,最好将其设置为一个集合,即items={}
嘿,谢谢你的回答,但这不起作用,它总是输出“Item not found”。你确定你在测试值的内容,而不仅仅是它的名称吗?如果items
中的数据是字符串,Chris的代码将起作用。如果尼尔的回答不能解决你的问题,你应该贴一个说明你问题的帖子。