简体   繁体   English

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

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

I have the following code:我有以下代码:

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")

I want the while loop to terminate if the number is in either the yes list or the no list.如果数字在yes no中,我希望while循环终止。 How can I include the second list in the while loop condition correctly?如何正确地将第二个列表包含在while循环条件中?

You can concatenate the lists using the addition operator:您可以使用加法运算符连接列表:

while answer not in yes + no:

You could also use and :您还可以使用and

while answer not in yes and answer not in no:

Also, there are other ways you can concatenate yes and no :此外,还有其他方法可以连接yesno

  • while answer not in [*yes, *no]:
  • You could add import itertools and check both the lists with while answer not in itertools.chain(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