python - 什么时候应该使用 list.count(0),如何打折 "False"项目?

标签 python list count boolean

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)

或(感谢 KevinBakuriu 的评论):

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 and is 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/

相关文章:

python - 将集合列表的项目添加到另一个集合

mysql - 从多个表中选择计数并分组

MySQL 使用 JOIN 语句计算匹配行数

mysql - rails COUNT SELECT DISTINCT

Python ctypes 回调函数给出 "TypeError: invalid result type for callback function"

python - numpy ndarray 的矩阵乘法

python - Airflow:如何从 Postgres Operator 插入 xcom 值(value)?

python - 数组比较与numpy中的元素比较不匹配

python - 如何最好地使用 Python 列表?

python - 有条件地从列表中删除元素