Python 如何使用 any 函数检查变量是否与列表中的任何项目匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22971667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:04:05  来源:igfitidea点击:

How to check if a variable matches any item in list using the any function?

pythonpython-2.x

提问by Aous1000

Edit: This is what I am trying to do: I am asking the user to enter a month. then the code will lookup if the month is correct by checking every item in months_list. If not found I want him/her to enter the month again..

编辑:这就是我想要做的:我要求用户输入一个月。然后代码将通过检查months_list中的每个项目来查找月份是否正确。如果没有找到,我希望他/她再次进入月份..

Here's the code:

这是代码:

months_list=["January", "February", "March", "April", "May", "June", "July"]
answer=raw_input("Month? \n")
while any(item.lower() != answer.lower() for item in months_list):
    print("Sorry, didn't recognize your answer, try again")
    answer=raw_input("Type in Month\n")

However this keeps looping regardless if the month is found in the list or not.. I hope this is a good clarifaction.. thank you all in advance

但是,无论是否在列表中找到月份,这都会循环播放.. 我希望这是一个很好的澄清.. 提前谢谢大家

采纳答案by martineau

The problem is that any()returns Trueif any oneof the elements in the iterable is True, so your code keeps looping as long as the answer isn't equal to allthe strings in months_list—which is probably the opposite of what you want to happen. Here's a way to use it that stops or breaks-out of the loop if the answer matches anyof the strings:

问题是,如果可迭代对象中的任何一个元素是 ,则any()返回,因此只要答案不等于其中的所有字符串,您的代码就会不断循环——这可能与您想要发生的情况相反。这是一种使用它的方法,如果答案与任何字符串匹配,则停止或中断循环:TrueTruemonths_list

months_list = ["January", "February", "March", "April", "May", "June", "July"]

while True:
    answer = raw_input("Month? ")
    if any(item.lower() == answer.lower() for item in months_list): 
        break
    print("Sorry, didn't recognize your answer, try again")

As others have pointed out, it would simpler to use Python's inoperator, however that way still results in a linear search, O(n), being performed...so an even better (faster) approach would be to use a setof lower-cased month_names, which would utilize a hash table based look-up, O(1), instead of a linear search:

正如其他人指出的那样,使用 Python 的in运算符会更简单,但是这种方式仍然会导致执行线性搜索 O(n)……所以更好(更快)的方法是使用 a setof lower- cased month_names,它将利用基于哈希表的查找,O(1),而不是线性搜索:

months = set(month.lower() for month in ("January", "February", "March", "April",
                                         "May", "June", "July"))
while True:
    answer = raw_input("Month? ")
    if answer.lower() in months: 
        break
    print("Sorry, didn't recognize your answer, try again")

回答by bgporter

To check membership, use in:

要检查成员资格,请使用in

>>> a = ['a','b','c','d']
>>> 'a' in a
True
>>> 'z' in a
False

回答by kindall

any(a)means "is any item in atruthy"? And the result is Truebecause every item in ais truthy. (Any non-zero-length string is truthy, and every item in ais a non-zero-length string.)

any(a)意思是“任何项目都是a真实的”?结果是True因为中的每个项目a都是真实的。(任何非零长度字符串都是真值,并且其中的每一项a都是非零长度字符串。)

And then you are comparing that result, True, to, say, "A". Trueis not equal to "A"so the result of thatcomparison is, of course, False.

然后你正在比较那个结果,True,比方说,"A"True不等于"A"这样的结果比较,当然,False

What you probably want to do is something like:

您可能想要做的是:

"A" in a   # True

If you must use any()for some reason, try:

如果any()由于某种原因必须使用,请尝试:

any(item == "A" for item in a)

This approach has the advantage of being able to do imprecise comparisons easily (inwill only do exact comparisons). For example:

这种方法的优点是能够轻松进行不精确的比较(in只会进行精确比较)。例如:

any(item.lower() == "a" for item in a)   # case-insensitive
any("a" in item.lower() for item in a)   # substring match
any(item.lower().startswith("a") for item in a)