【问题标题】:If an input is part of a list [duplicate]如果输入是列表的一部分[重复]
【发布时间】:2016-10-25 09:29:14
【问题描述】:

我被困在这部分代码上。这是示例文本的示例

items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if choice != items:
    print("Item not found")
else:
    print("Item found")

这是我想做的一个例子。我想弄清楚用户输入的内容是否是给定列表的一部分。这是python 3.5

【问题讨论】:

  • 应该是if choice not in items。如果items 很大,最好将其设置为一组,即items = {}
  • 您好,感谢您的回复,但这不起作用,它总是输出“找不到项目”。
  • 您确定要测试值的内容,而不仅仅是其名称吗?
  • 如果items 中的数据是字符串,Chris 的代码将起作用。如果尼尔的回答不能解决您的问题,您应该发布一个 minimal reproducible example 来说明您的问题。

标签: python list python-3.x


【解决方案1】:

这将取决于列表中的数据类型。 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 必须是:

items = [variable1, variable2, variable3]
choice = input("Input variable here: ")
if float(choice) not in items:
    print("Item not found")
else:
    print("Item found")

这现在应该正确地评估 if 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多