简体   繁体   English

如何计算列表中“None”的出现次数?

[英]How to count the number of occurrences of `None` in a list?

I'm trying to count things that are not None , but I want False and numeric zeros to be accepted too.我正在尝试计算不是None的东西,但我也希望接受False和数字零。 Reversed logic: I want to count everything except what it's been explicitly declared as None .反向逻辑:我想计算除明确声明为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 ,但没有运气。

Just use sum checking if each object is not None which will be True or False so 1 or 0.只需使用sum检查每个对象is not None这将是TrueFalse所以 1 或 0。

lst = ['hey','what',0,False,None,14]
print(sum(x is not None for x in lst))

Or using filter with python2:或者在 python2 中使用filter

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

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)
lst = ['hey','what',0,False,None,14]
print sum(1 for i in lst if i != None)

You could use Counter from collections .您可以使用collections Counter

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

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,因为我也使用了助手is_Noneis_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

Use numpy使用 numpy

import numpy as np

list = np.array(['hey', 'what', 0, False, None, 14])
print(sum(list != None))

I needed to make sure that only one param was send on each call.我需要确保每次调用只发送一个参数。 Therefore at least 2 of the variables must be None and this worked for me.因此,至少有 2 个变量必须为 None,这对我有用。

a_list = [param_1, param_2, param_3] 
count = a_list.count(None) 
if count < 2:
    raise error

im pretty sure that using the length of the list minus the number of Nones here sould be the best option for performance and simplicity我很确定使用列表的长度减去 Nones 的数量是性能和简单性的最佳选择

>>> list = ['hey', 'what', 0, False, None, 14]
>>> print(len(list) - list.count(None))
5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM