简体   繁体   中英

LIST.count() in Python

Dears, please need help in count method if

LIST=[0,0.0,False,[],(),{},1,1.1,True]

and if using .count and searching on 0 or 0.0 or False

--- LIST.count(0) or LIST.count(0.0) or LIST.count(False) ---

return 3 only not 6, while there are another 3 elements Consider as False : [] , () , {} as below bool Function

if we used bool([]) or bool(()) or bool({}) to know its Boolean Value will Return False

also I Tried to Check

print([] == False) | print(() == False) | print({} == False) 

will return False not True

I am not sure of what your final goal is, but looking for zero (False) using the .count method, you can create another list by transforming the original elements to boolean

>>> lst = [0, 0.0, False, [], (), {}, 1, 1.1, True] 
>>> l = [bool(el) for el in lst]
>>> l.count(0)
6
>>> l.count(False)
6

If you want to count both True and False equivalents you can rely on the standard library using collections.Counter

>>> import collections as co
>>> c = co.Counter(map(bool, lst))
>>> c[False]
6
>>> c[True]
3

A fun iterator way to count false elements:

false = 0
it = iter(LIST)
while not all(it):
    false += 1

Or a boring normal way:

false = sum(1 for x in LIST if not x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM