a.count(0)
总是返回 11,那么我应该怎么做才能打折 False
并返回 10?
a = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
最佳答案
Python 2.x 将 False
解释为 0
,反之亦然。 AFAIK 甚至 None
和 ""
在条件下都可以被视为 False
。
重新定义计数如下:
sum(1 for item in a if item == 0 and type(item) == int)
sum(1 for item in a if item == 0 and type(item) is type(0))
或按照 ozgur 的建议在评论中(不推荐并且被认为是错误的,参见 this),简单地说:
sum(1 for item in a if item is 0)
可能 (“is” operator behaves unexpectedly with integers) 适用于small 主要类型,但如果您的列表包含对象,请考虑 is
运算符的作用:
来自 is
operator 的文档:
The operators
is
andis not
test for object identity:x is y
is true if and only if x and y are the same object.
关于 is
运算符的更多信息:Understanding Python's "is" operator
关于python - 什么时候应该使用 list.count(0),如何打折 "False"项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39404581/