区分的唯一方法是通过它们的类型:
>>> type(False)
bool
>>> type(0)
int
但是isinstance 不能用于0,因为bool 是int 的子类
>>> isinstance(0, bool)
False
>>> isinstance(False, int)
True
而且值是相等的(这就是为什么count 不能“正确”为您工作):
>>> 0 == False
True
您可以使用 0 是 CPython(可能还有其他 Python 实现)中的内部(单例)整数和 False 也是单例的事实:
>>> 0 is 0
True
>>> False is False
True
>>> 0 is False
False
至于解决方案:使用不等于的东西,例如None:
arr = [0, None, None, 0, None]
arr.count(0) # 2
arr.count(None) # 3
如果你真的需要使用0 和False,你可以使用sum(就像其他人展示的那样):
sum(x is False for x in arr) # for count(False)
sum(x is 0 for x in arr) # for count(0)
或独立于 Python 实现:type 和值作为标识符和 collections.Counter:
>>> arr = [0, False, False, 0, False]
>>> from collections import Counter
>>> Counter((type(x), x) for x in arr)
Counter({(bool, False): 3, (int, 0): 2})