繁体   English   中英

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

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

我想选择许多给定的数字并将它们与我选择的数字进行比较,我如何使用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')

输入以下内容,我无法获得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.

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