计算 Python 列表中真布尔值的数量

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

Counting the number of True Booleans in a Python List

pythonlistbooleancounting

提问by acs

I have a list of Booleans:

我有一个布尔列表:

[True, True, False, False, False, True]

and I am looking for a way to count the number of Truein the list (so in the example above, I want the return to be 3.) I have found examples of looking for the number of occurrences of specific elements, but is there a more efficient way to do it since I'm working with Booleans? I'm thinking of something analogous to allor any.

并且我正在寻找一种方法来计算True列表中的数量(因此在上面的示例中,我希望返回为3。)我找到了寻找特定元素出现次数的示例,但是还有更多因为我正在使用布尔值,所以这样做的有效方法是什么?我在想类似于all或的东西any

采纳答案by Ignacio Vazquez-Abrams

Trueis equal to 1.

True等于1

>>> sum([True, True, False, False, False, True])
3

回答by Blender

You can use sum():

您可以使用sum()

>>> sum([True, True, False, False, False, True])
3

回答by Ned Deily

If you are only concerned with the constant True, a simple sumis fine. However, keep in mind that in Python other values evaluate as Trueas well. A more robust solution would be to use the boolbuiltin:

如果您只关心常量True,简单的sum就可以了。但是,请记住,在 Python 中,其他值True也会计算。更强大的解决方案是使用bool内置函数:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

更新:这是另一个同样强大的解决方案,其优点是更加透明:

>>> sum(1 for x in l if x)
3

P.S. Python trivia: Truecouldbe true without being 1. Warning: do not try this at work!

PS Python 琐事:True如果不为 1也可能是真的。警告:不要在工作中尝试这个!

>>> True = 2
>>> if True: print('true')
... 
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3

Much more evil:

更邪恶:

True = False

回答by kampu

I prefer len([b for b in boollist if b is True])(or the generator-expression equivalent), as it's quite self-explanatory. Less 'magical' than the answer proposed by Ignacio Vazquez-Abrams.

我更喜欢len([b for b in boollist if b is True])(或生成器表达式等价物),因为它是不言自明的。比 Ignacio Vazquez-Abrams 提出的答案更“神奇”。

Alternatively, you can do this, which still assumes that bool is convertable to int, but makes no assumptions about the value of True: ntrue = sum(boollist) / int(True)

或者,您可以这样做,它仍然假设 bool 可转换为 int,但不对 True 的值做任何假设: ntrue = sum(boollist) / int(True)

回答by Mark Tolonen

listhas a countmethod:

list有一个count方法:

>>> [True,True,False].count(True)
2

This is actually more efficient than sum, as well as being more explicit about the intent, so there's no reason to use sum:

这实际上比 更有效sum,并且对意图更明确,因此没有理由使用sum

In [1]: import random

In [2]: x = [random.choice([True, False]) for i in range(100)]

In [3]: %timeit x.count(True)
970 ns ± 41.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit sum(x)
1.72 μs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

回答by Mark Tolonen

It is safer to run through boolfirst. This is easily done:

先跑过去比较安全bool。这很容易做到:

>>> sum(map(bool,[True, True, False, False, False, True]))
3

Then you will catch everything that Python considers True or False into the appropriate bucket:

然后,您将把 Python 认为是 True 或 False 的所有内容都捕获到适当的存储桶中:

>>> allTrue=[True, not False, True+1,'0', ' ', 1, [0], {0:0}, set([0])]
>>> list(map(bool,allTrue))
[True, True, True, True, True, True, True, True, True]

If you prefer, you can use a comprehension:

如果您愿意,可以使用理解式:

>>> allFalse=['',[],{},False,0,set(),(), not True, True-1]
>>> [bool(i) for i in allFalse]
[False, False, False, False, False, False, False, False, False]

回答by yoniLavi

Just for completeness' sake (sumis usually preferable), I wanted to mention that we can also use filterto get the truthy values. In the usual case, filteraccepts a function as the first argument, but if you pass it None, it will filter for all "truthy" values. This feature is somewhat surprising, but is well documented and works in both Python 2 and 3.

只是为了完整起见(sum通常更可取),我想提一下我们也可以filter用来获取真实值。通常情况下,filter接受一个函数作为第一个参数,但如果你传递它None,它将过滤所有“真实”值。这个特性有点令人惊讶,但有很好的文档记录并且可以在 Python 2 和 3 中使用。

The difference between the versions, is that in Python 2 filterreturns a list, so we can use len:

版本之间的区别在于,在 Python 2 中filter返回一个列表,因此我们可以使用len

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
[True, True, True]
>>> len(filter(None, bool_list))
3

But in Python 3, filterreturns an iterator, so we can't use len, and if we want to avoid using sum(for any reason) we need to resort to converting the iterator to a list (which makes this much less pretty):

但是在 Python 3 中,filter返回一个迭代器,所以我们不能使用len,如果我们想避免使用sum(出于任何原因),我们需要将迭代器转换为列表(这使得它变得不那么漂亮):

>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
<builtins.filter at 0x7f64feba5710>
>>> list(filter(None, bool_list))
[True, True, True]
>>> len(list(filter(None, bool_list)))
3

回答by GMishx

After reading all the answers and comments on this question, I thought to do a small experiment.

看完这个问题的所有答案和评论后,我想做一个小实验。

I generated 50,000 random booleans and called sumand counton them.

我产生50000个随机布尔值,并呼吁sumcount他们。

Here are my results:

这是我的结果:

>>> a = [bool(random.getrandbits(1)) for x in range(50000)]
>>> len(a)
50000
>>> a.count(False)
24884
>>> a.count(True)
25116
>>> def count_it(a):
...   curr = time.time()
...   counting = a.count(True)
...   print("Count it = " + str(time.time() - curr))
...   return counting
... 
>>> def sum_it(a):
...   curr = time.time()
...   counting = sum(a)
...   print("Sum it = " + str(time.time() - curr))
...   return counting
... 
>>> count_it(a)
Count it = 0.00121307373046875
25015
>>> sum_it(a)
Sum it = 0.004102230072021484
25015

Just to be sure, I repeated it several more times:

可以肯定的是,我又重复了几次:

>>> count_it(a)
Count it = 0.0013530254364013672
25015
>>> count_it(a)
Count it = 0.0014507770538330078
25015
>>> count_it(a)
Count it = 0.0013344287872314453
25015
>>> sum_it(a)
Sum it = 0.003480195999145508
25015
>>> sum_it(a)
Sum it = 0.0035257339477539062
25015
>>> sum_it(a)
Sum it = 0.003350496292114258
25015
>>> sum_it(a)
Sum it = 0.003744363784790039
25015

And as you can see, countis 3 times faster than sum. So I would suggest to use countas I did in count_it.

正如您所看到的,count比 快 3 倍sum。所以我建议count像我在count_it.

Python version: 3.6.7
CPU cores: 4
RAM size: 16 GB
OS: Ubuntu 18.04.1 LTS

Python 版本:3.6.7
CPU 内核:4
RAM 大小:16 GB
操作系统:Ubuntu 18.04.1 LTS