简体   繁体   中英

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. How can I include the second list in the while loop condition correctly?

You can concatenate the lists using the addition operator:

while answer not in yes + no:

You could also use and :

while answer not in yes and answer not in no:

Also, there are other ways you can concatenate yes and no :

  • 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):
  • while answer not in [j for i in zip(yes, no) for j in i]:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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