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

时间:2015-04-02 21:21:19

标签: python boolean list-comprehension nonetype

我正在尝试计算不是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,但没有运气。

6 个答案:

答案 0 :(得分:28)

只需使用sum检查每个对象is not NoneTrue还是False所以1或0。

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

或者使用filter和python2:

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

使用python3时, None.__ne__() 只会忽略无法过滤而不需要lambda。

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

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

在旁注中避免使用list作为变量名称,因为它会影响python list

答案 1 :(得分:9)

两种方式:

一,带有列表表达式

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

两个,计算Nones并从长度中减去它们:

len(lst) - lst.count(None)

答案 2 :(得分:3)

lst = ['hey','what',0,False,None,14]
print sum(1 for i in lst if i != None)

答案 3 :(得分:1)

您可以使用Counter中的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

答案 4 :(得分:0)

我最近发布了一个包含函数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 :(得分:0)

使用numpy

chars = []
not_capitalize = set(['is', 'and']) # you can put other words in here that you don't want to capitalize

# split will create an array of words split on spaces
for char in mystr.split():
    if char in not_capitalize:
        chars.append(char)
        continue

    # Separate the first letter from the rest of the word
    first_letter, rest = char[0], char[1:]

    # stitch the uppercase first_letter with the rest of the word together
    chars.append("%s%s"% (first_letter.upper(), rest))

# join and print
print(' '.join(chars))

# Gives The Sky is Blue