Counting the number of True Booleans in a Python List

前端 未结 8 1073
没有蜡笔的小新
没有蜡笔的小新 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:27

    list has a count method:

    >>> [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:

    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)
    

提交回复
热议问题