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

如何在Python中计算整数列表中的真值?,python,list,count,boolean,Python,List,Count,Boolean,有人能解释一下为什么在for in l5循环中我得到了2个真值,但从l5.count(真)中我只得到了1??为什么l5.count(不是0)只返回1 我知道获取所需信息的其他方法:filter+lambda或sum+for+if,但我试着理解它:) 在Python控制台的部分下,我已经问过了 win32上的Python 3.9.0(tags/v3.9.0:9cf6752,2020年10月5日,15:34:40)[MSC v.1927 64位(AMD64)] ''' python中的''False

有人能解释一下为什么在
for in l5
循环中我得到了2个真值,但从
l5.count(真)
中我只得到了1??为什么
l5.count(不是0)
只返回1

我知道获取所需信息的其他方法:filter+lambda或sum+for+if,但我试着理解它:)

在Python控制台的部分下,我已经问过了

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


python中的''

False
在数字上等于
0
True
在数字上等于
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(True)

用列表中的每个元素检查它
l5

0==True ?
0==True ?
0==True ?
1==True ?
2==True ?
现在,由于
True
bool
类型,而其他类型是
int
,python执行从
bool
int
的隐式类型转换(比较类型应该是相同的)

因此,
True
在数字上等同于
1

Count=0

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

Final output : 1
现在是从
bool
int

在从
int
bool
的转换中:

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

您可以阅读有关此的更多信息

count(True)
将只列出1个值,因为列表中只有“1”(True)。但是
bool(x)
将为x的每一个非零值返回1。这就是为什么你有两个true(s)。仅仅因为你可以对列表中的项目调用
bool
,结果是
true
False
,并不意味着列表实际上包含这些boolean。我不清楚,但现在我明白了列表中的“2”发生了什么。谢谢你们的帮助。
Count=0

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

Final output : 1
>>> 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