繁体   English   中英

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

[英]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]:

暂无
暂无

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

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