简体   繁体   English

试图了解如何使用any()函数

[英]Trying to understand how to use the any() function

I want to pick many given numbers and compare them to a number I chose, how do i do this using the any or all command , I tried this and it didn't work, any input would be appreciated: 我想选择许多给定的数字并将它们与我选择的数字进行比较,我如何使用anyall命令来执行此操作,我尝试了此操作,但它不起作用,将不胜感激任何输入:

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

Entering the following, I can't get the if to evaluate to True : 输入以下内容,我无法获得if的评估结果为True

What number are you looking for ?5
What is the first number1
What is the second number2
What is the third number5
>>> 

How am I using any wrong here ? 我如何使用any错在这里? Since the last number is 5 I should of gotten a hit but I get nothing. 由于最后一个数字是5我应该受到打击,但我什么也没得到。

Because you're using any wrong. 因为您使用的是any错误。 To achieve what you want, supply the condition to any : 要实现所需的条件,请为以下any条件提供条件:

if any(v == i for i in [a, b, c]):
   print('We got a hit')

This will check that there's a value in the list [a, b, c] which equals v . 这将检查列表[a, b, c]中是否存在等于v

Your approach: 您的方法:

any([a, b, c]) == v

Will first use any to check if any of the elements inside the iterable ( [a, b, c] ) supplied has a truthy value (and it does, all of them do if they're positive integers) and returns the appropriate result True indicating that. 首先将使用any来检查提供的iterable( [a, b, c] )内部的任何元素是否具有真实值(并且确实如此,如果它们都是正整数,则所有元素都可以)并返回适当的结果True表明这一点。 So: 所以:

any([a, b, c])

will return True . 将返回True Your condition then becomes: 您的条件将变为:

True == v

which obviously evaluates to False . 显然评估为False

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

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