Counting the number of True Booleans in a Python List

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

    True is equal to 1.

    >>> sum([True, True, False, False, False, True])
    3
    
    0 讨论(0)
  • 2020-12-08 09:40

    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.

    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)

    0 讨论(0)
提交回复
热议问题