什么是逻辑上结合布尔列表的最"pythonic"方式?

Bob*_*obC 31 python boolean list

我有一个布尔列表我想用逻辑组合使用和/或.扩展的业务将是:

vals = [True, False, True, True, True, False]

# And-ing them together
result = True
for item in vals:
    result = result and item

# Or-ing them together
result = False
for item in vals:
    result = result or item
Run Code Online (Sandbox Code Playgroud)

上面的每一个都有漂亮的单行吗?

Nul*_*ion 83

all(iterable):

返回True如果的所有元素 迭代是真实的(或者如果可迭代 为空).

而且any(iterable):

True如果iterable的任何元素为true ,则 返回.如果iterable为空,则返回False.


Jer*_*rub 6

最好的方法是使用any()all()功能.

vals = [True, False, True, True, True]
if any(vals):
   print "any() reckons there's something true in the list."
if all(vals):
   print "all() reckons there's no non-True values in the list."
if any(x % 4 for x in range(100)):
   print "One of the numbers between 0 and 99 is divisible by 4."
Run Code Online (Sandbox Code Playgroud)