在逻辑上组合布尔值列表的最“pythonic”方式是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3673337/
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-18 12:10:08  来源:igfitidea点击:

What is the most 'pythonic' way to logically combine a list of booleans?

pythonlistboolean

提问by BobC

I have a list of booleans I'd like to logically combine using and/or. The expanded operations would be:

我有一个布尔值列表,我想使用和/或逻辑组合。扩展的操作将是:

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

Are there nifty one-liners for each of the above?

以上每种都有漂亮的单衬吗?

采纳答案by NullUserException

See all(iterable):

all(iterable)

Return Trueif all elements of the iterableare true (or if the iterableis empty).

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

And any(iterable):

并且any(iterable)

Return Trueif any element of the iterableis true. If the iterableis empty, return False.

True如果迭代的任何元素为真,则 返回。如果可迭代对象为空,则返回False

回答by Jerub

The best way to do it is with the any()and all()functions.

最好的方法是使用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."