Counting the number of True Booleans in a Python List

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

    It is safer to run through bool first. This is easily done:

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

    >>> 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]
    

提交回复
热议问题