如何检查一个值是否存在于多个列表之一中

How to check if a value exists in one of several lists

我有以下代码:

answer = int(input("input number in range 1-6: "))
yes = [1, 2, 3]
no = [4, 5, 6]
while answer not in yes:
    print("what?")
    answer = int(input())
else:
    if answer in no:
        print("no")
    elif answer in yes:
        print("yes")

如果数字在 yes 列表或 no 列表中,我希望 while 循环终止。如何在 while 循环条件中正确包含第二个列表?

您可以使用加法运算符连接列表:

while answer not in yes + no:

您也可以使用 and:

while answer not in yes and answer not in no:

此外,还有其他方法可以连接 yesno:

  • while answer not in [*yes, *no]:
  • 您可以添加 import itertools 并使用 while answer not in itertools.chain(yes, no):
  • 检查两个列表
  • while answer not in [j for i in zip(yes, no) for j in i]: