测试 python 列表的所有元素是否都是 False

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

Test if all elements of a python list are False

pythonlistnumpy

提问by thunder

How to return 'false' because all elements are 'false'?

如何返回“假”,因为所有元素都是“假”?

The given list is:

给定的列表是:

data = [False, False, False]

采纳答案by falsetru

Using any:

使用any

>>> data = [False, False, False]
>>> not any(data)
True

anywill return True if there's any truth value in the iterable.

any如果可迭代对象中有任何真值,则将返回 True。

回答by Alexey Orlenko

Basically there are two functions that deal with an iterable and return True or False depending on which boolean values elements of the sequence evaluate to.

基本上有两个函数可以处理可迭代对象并根据序列的哪个布尔值元素计算结果返回 True 或 False。

  1. all(iterable)returns True if all elements of the iterableare considered as true values (like reduce(operator.and_, iterable)).

  2. any(iterable)returns True if at least one element of the iterableis a true value (again, using functional stuff, reduce(operator.or_, iterable)).

  1. all(iterable)如果 的所有元素iterable都被视为真值(如reduce(operator.and_, iterable)),则返回 True 。

  2. any(iterable)如果 的至少一个元素iterable是真值,则返回 True (同样,使用函数式的东西,reduce(operator.or_, iterable))。

Using the allfunction, you can map operator.not_over your list or just build a new sequence with negated values and check that all the elements of the new sequence are true:

使用该all函数,您可以映射operator.not_您的列表或仅构建一个带有否定值的新序列并检查新序列的所有元素是否为真:

>>> all(not element for element in data)

With the anyfunction, you can check that at least one element is true and then negate the result since you need to return Falseif there's a true element:

使用该any函数,您可以检查至少一个元素为真,然后否定结果,因为False如果有真元素,您需要返回:

>>> not any(data)

According to De Morgan's law, these two variants will return the same result, but I would prefer the last one (which uses any) because it is shorter, more readable (and can be intuitively understood as "there isn't a true value in data") and more efficient (since you don't build any extra sequences).

根据德摩根定律,这两个变体将返回相同的结果,但我更喜欢最后一个(使用any),因为它更短,更具可读性(并且可以直观地理解为“数据中没有真正的价值") 并且更高效(因为您不构建任何额外的序列)。

回答by Oscar Developper

Come on, guys, he asked for returning True whether there was any True. Saying the same, False when all are False.

来吧,伙计们,他要求返回 True 是否有任何 True。说同样的,当所有都是假的时候是假的。

any(data)