簡體   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