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

标签 python python-2.x

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

代码如下:

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

然而,无论是否在列表中找到月份,它都会一直循环。我希望这是一个很好的说明。提前谢谢大家

最佳答案

问题在于,如果可迭代对象中的任何一个元素为True,则any() 返回True >,所以只要答案不等于 all months_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")

正如其他人所指出的,虽然使用 Python 的 in 运算符会更简单,但这种方式仍然会导致线性搜索,O(n),正在执行……所以更好(更快)的方法是使用小写的 month_namesset,这将利用基于哈希表的外观-向上,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")

进一步细化

根据所涉及字符串的性质以及比较它们的原因,最好使用字符串 casefold()方法而不是 lower() 来进行不区分大小写的字符串比较。

关于python - 如何使用 any() 函数检查变量是否与列表中的任何项目匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22971667/

相关文章:

Python线程/守护进程

基于循环计数器的python matplotlib轴标签下标

python - 在 OSX 10.10 上链接 Boost Python

python - 如何使用 related_name 查询 M2M

python - 在终端上使用 __repr__ 转换显示对象的 unicode 字符串

python - 结合多重继承使用元类的类型错误

python - 在设计猜猜 python 中的数字列表的游戏时遇到麻烦

python - 透明地将值分配给自定义数字类型

python - 在第 n 次出现后删除字符串的其余部分

Python 2 CSV 编写器在 Windows 上产生错误的行终止符