如何在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