【问题标题】:How to count the number of occurrences of `None` in a list?如何计算列表中“无”的出现次数?
【发布时间】:2015-06-07 23:35:32
【问题描述】:

我正在尝试计算不是None 的东西,但我希望False 和数字零也被接受。逆向逻辑:除了明确声明为None 的内容之外,我想计算所有内容。

示例

只是第 5 个元素不包含在计数中:

>>> list = ['hey', 'what', 0, False, None, 14]
>>> print(magic_count(list))
5

我知道这不是 Python 的正常行为,但是如何覆盖 Python 的行为?

我尝试过的

到目前为止,我发现有人建议 a if a is not None else "too bad",但它不起作用。

我也尝试过isinstance,但没有成功。

【问题讨论】:

    标签: python boolean list-comprehension nonetype


    【解决方案1】:

    只需使用 sum 检查每个对象 is not None 是否为 TrueFalse 所以 1 或 0。

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

    或者在 python2 中使用filter

    print(len(filter(lambda x: x is not None, lst))) # py3 -> tuple(filter(lambda x: x is not None, lst))
    

    在 python3 中,None.__ne__() 只会忽略 None 并过滤而不需要 lambda。

    sum(1 for _ in filter(None.__ne__, lst))
    

    sum 的优点是它一次懒惰地评估一个元素,而不是创建一个完整的值列表。

    附带说明避免使用list 作为变量名,因为它会影响python list

    【讨论】:

    • 第二种方法在TypeError: object of type 'filter' has no len()987654333@中的 Python 3 中失败
    • @SeppoEnarvi。那是因为 python3 中的 filter 返回一个过滤器对象,它是一个迭代器,而不是一个列表。我添加了另一种特定于 py3 的方式来过滤 None。
    • 谢谢!我没有意识到你可以使用这样的“列表理解”。一个澄清 - 我实际上发现它在没有print() 的情况下效果更好。只需使用sum(x is not None for x in lst),它就会返回一个 int 而不是 NoneType。
    【解决方案2】:
    lst = ['hey','what',0,False,None,14]
    print sum(1 for i in lst if i != None)
    

    【讨论】:

    • 这个是如何统计有多少列表元素不等于None
    • 作者想统计非None的东西。在 Python 语句中,obj != None 和 obj is not None 是等价的。
    • 是的,你是唯一一个没有把False 算为零的人。 (那是赞美,而不是更正;-)
    【解决方案3】:

    两种方式:

    一个,带列表表达式

    len([x for x in lst if x is not None])
    

    二,计算无数并从长度中减去它们:

    len(lst) - lst.count(None)
    

    【讨论】:

    • 我认为你的第一个解决方案是最 Pythonic 的,应该是公认的答案
    • 你的第二个选项应该更多地使用。它只是更快
    【解决方案4】:

    我最近发布了一个库,其中包含一个函数 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
    

    【讨论】:

      【解决方案5】:

      使用 numpy

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

      【讨论】:

        【解决方案6】:

        你可以使用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
        

        【讨论】:

          猜你喜欢
          • 2021-07-29
          • 2012-07-12
          • 1970-01-01
          • 2023-01-12
          • 1970-01-01
          • 2011-02-05
          相关资源
          最近更新 更多