Counting the number of True Booleans in a Python List

前端 未结 8 1056
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 09:08

I have a list of Booleans:

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

and I am looking for a way to count the number of True in t

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 09:19

    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 sum and count on them.

    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, count is 3 times faster than sum. So I would suggest to use count as I did in count_it.

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

提交回复
热议问题