[英]Trying to understand how to use the any() function
我想選擇許多給定的數字並將它們與我選擇的數字進行比較,我如何使用any
或all
命令來執行此操作,我嘗試了此操作,但它不起作用,將不勝感激任何輸入:
import random
v = int(input("What number are you looking for ?"))
a1 = int(input("What is the first number"))
a2 = int(input("What is the second number"))
a3 = int(input("What is the third number"))
a = random.choice([a1,a2,a3])
b = random.choice([a1,a2,a3])
c = random.choice([a1,a2,a3])
if any ([a, b, c]) == v:
print('We got a hit')
輸入以下內容,我無法獲得if
的評估結果為True
:
What number are you looking for ?5
What is the first number1
What is the second number2
What is the third number5
>>>
我如何使用any
錯在這里? 由於最后一個數字是5
我應該受到打擊,但我什么也沒得到。
因為您使用的是any
錯誤。 要實現所需的條件,請為以下any
條件提供條件:
if any(v == i for i in [a, b, c]):
print('We got a hit')
這將檢查列表[a, b, c]
中是否存在等於v
。
您的方法:
any([a, b, c]) == v
首先將使用any
來檢查提供的iterable( [a, b, c]
)內部的任何元素是否具有真實值(並且確實如此,如果它們都是正整數,則所有元素都可以)並返回適當的結果True
表明這一點。 所以:
any([a, b, c])
將返回True
。 您的條件將變為:
True == v
顯然評估為False
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.