Python 如何计算列表中“无”的出现次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29422691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count the number of occurrences of `None` in a list?
提问by Hrabal
I'm trying to count things that are not None
, but I want False
and numeric zeros to be accepted too. Reversed logic: I want to count everything except what it's been explicitly declared as None
.
我正在尝试计算不是的东西None
,但我也希望False
数字零也被接受。反向逻辑:我想计算除明确声明为None
.
Example
例子
Just the 5th element it's not included in the count:
只有第 5 个元素不包含在计数中:
>>> list = ['hey', 'what', 0, False, None, 14]
>>> print(magic_count(list))
5
I know this isn't Python normal behavior, but how can I override Python's behavior?
我知道这不是 Python 的正常行为,但是如何覆盖 Python 的行为?
What I've tried
我试过的
So far I founded people suggesting that a if a is not None else "too bad"
, but it does not work.
到目前为止,我发现有人建议这样做a if a is not None else "too bad"
,但它不起作用。
I've also tried isinstance
, but with no luck.
我也试过isinstance
,但没有运气。
采纳答案by Padraic Cunningham
Just use sum
checking if each object is not None
which will be True
or False
so 1 or 0.
只是使用sum
检查是否每个对象is not None
,这将是True
或False
所以1或0。
lst = ['hey','what',0,False,None,14]
print(sum(x is not None for x in lst))
Or using filter
with python2:
或filter
与 python2 一起使用:
print(len(filter(lambda x: x is not None, lst))) # py3 -> tuple(filter(lambda x: x is not None, lst))
With python3 there is None.__ne__()
which will only ignore None's and filter without the need for a lambda.
使用 python3, None.__ne__()
它只会忽略 None 和过滤器,而无需 lambda。
sum(1 for _ in filter(None.__ne__, lst))
The advantage of sum
is it lazily evaluates an element at a time instead of creating a full list of values.
的优点sum
是它一次懒惰地评估一个元素,而不是创建一个完整的值列表。
On a side note avoid using list
as a variable name as it shadows the python list
.
在旁注中避免list
用作变量名,因为它会影响 python list
。
回答by kvorobiev
lst = ['hey','what',0,False,None,14]
print sum(1 for i in lst if i != None)
回答by RemcoGerlich
Two ways:
两种方式:
One, with a list expression
一、用列表表达式
len([x for x in lst if x is not None])
Two, count the Nones and subtract them from the length:
二、数数 Nones 并从长度中减去它们:
len(lst) - lst.count(None)
回答by MSeifert
I recently released a library containing a function iteration_utilities.count_items
(ok, actually 3 because I also use the helpers is_None
and is_not_None
) for that purpose:
我最近发布了一个包含一个函数的库iteration_utilities.count_items
(好吧,实际上是 3,因为我也使用了 helpersis_None
和is_not_None
)用于这个目的:
>>> from iteration_utilities import count_items, is_not_None, is_None
>>> lst = ['hey', 'what', 0, False, None, 14]
>>> count_items(lst, pred=is_not_None) # number of items that are not None
5
>>> count_items(lst, pred=is_None) # number of items that are None
1
回答by Rémi Baudoux
Use numpy
使用 numpy
import numpy as np
list = np.array(['hey', 'what', 0, False, None, 14])
print(sum(list != None))
回答by Vikto
You could use Counter
from collections
.
您可以使用Counter
from collections
.
from collections import Counter
my_list = ['foo', 'bar', 'foo', None, None]
resulted_counter = Counter(my_list) # {'foo': 2, 'bar': 1, None: 2}
resulted_counter[None] # 2