![](/img/trans.png)
[英]How do I apply a condition to change the values of a list of variables? - Python
[英]How do you apply 'or' to all values of a list in Python?
如何在Python中对列表的所有值应用'或'? 我想的是:
or([True, True, False])
或者如果可能的话:
reduce(or, [True, True, False])
内置函数any
可以满足您的需求:
>>> any([True, True, False])
True
>>> any([False, False, False])
False
>>> any([False, False, True])
True
一旦找到真值, any
都有利于reduce
对序列中后续项目的测试的快捷方式。 如果序列是一个后面有昂贵操作的发生器,这可能非常方便。 例如:
>>> def iam(result):
... # Pretend this is expensive.
... print "iam(%r)" % result
... return result
...
>>> any((iam(x) for x in [False, True, False]))
iam(False)
iam(True)
True
>>> reduce(lambda x,y: x or y, (iam(x) for x in [False, True, False]))
iam(False)
iam(True)
iam(False)
True
如果您的Python版本没有any()
, all()
内置,那么它们很容易实现,如Guido van Rossum所建议 :
def any(S):
for x in S:
if x:
return True
return False
def all(S):
for x in S:
if not x:
return False
return True
没有人提到它,但“ or
”在操作员模块中可用作功能:
from operator import or_
然后你可以使用如上所述的reduce
。
尽管在最近的Pythons中,总会建议“ any
”。
>>> all([True,False,True])
False
>>> any([True,False,True])
True
Python 2.5及更高版本( 文档 )
你可以这样做:
reduce(lambda a,b: a or b, [True, True, False])
减少应该为你做,不应该吗?
>>> def _or(x, y):
... return x or y
...
>>> reduce(_or, [True, True, False])
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.