Counting the number of True Booleans in a Python List

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

    Just for completeness' sake (sum is usually preferable), I wanted to mention that we can also use filter to get the truthy values. In the usual case, filter accepts 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.

    The difference between the versions, is that in Python 2 filter returns a list, so we can use 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, filter returns 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):

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

提交回复
热议问题