如何计算 Python 中整数列表中的真值?

How work counting True values in list of ints in Python?

有人能解释一下为什么在 for in l5 循环中我得到了 2 个真值,但在 l5.count(True) 中我只有 1 个吗?为什么 l5.count(not 0) returns 只有 1 个?

我知道其他方法来获得我需要的东西:filter + lambda 或 sum + for + if,但我试着理解它:)

我问过 Python 控制台的一部分。

Python 3.9.0(tags/v3.9.0:9cf6752,2020 年 10 月 5 日,15:34:40)[MSC v.1927 64 位 (AMD64)]在 win32 '''

l5 = [0, 0, 0, 1, 2]
l5.count(True)
Out[3]: 1
for x in l5:
    print(x, bool(x))
    
0 False
0 False
0 False
1 True
2 True
l5.count(0)
Out[5]: 3
l5.count(not 0)
Out[6]: 1
l5.count(not False)
Out[7]: 1

'''

False在python数值上等于0True在数值上等于1.

所以 not False 将等于 True,这将在数值上等于 1

l5 = [0, 0, 0, 1, 2]
l5.count(True) # is equivalent to l5.count(1)
Out[3]: 1
l5.count(not 0) # is equivalent to l5.count(1)
Out[6]: 1
l5.count(not False) # is equivalent to l5.count(1)
Out[7]: 1

还有

l5.count(False) # is equivalent to l5.count(0)
Out[8]: 3

当你做 l5.count(True)

内部python检查列表中的每个元素l5

0==True ?
0==True ?
0==True ?
1==True ?
2==True ?

现在 Truebool 类型而其他类型是 int,python 执行从 boolint 的隐式类型转换(至于做比较类型应该是一样的)

因此 True 在数值上等同于 1:

Count=0

0==1 ? No
0==1 ? No
0==1 ? No
1==1 ? Yes; Count += 1 
2==1 ? No

Final output : 1

现在这是从 boolint

的类型转换

在从 intbool 的转换中:

0 被视为 False 并且除 0 之外的所有内容,-1,-2,-3,... 1,2,3,.. 都被处理作为 True.

等等

>>> bool(-1)
True

>>> bool(1)
True

>>> bool(2)
True

>>> bool(0)
False

>>> not 2
False

# as 2 is equivalent to True and "not True" is False

您可以阅读更多相关内容 here