列表中的值大于某个数字的数量

zac*_*ach 57 python list

我有一个数字列表,我想得到一个数字出现在符合特定条件的列表中的次数.我可以使用列表理解(或函数中的列表理解),但我想知道是否有人有更短的方式.

# list of numbers
j=[4,5,6,7,1,3,7,5]
#list comprehension of values of j > 5
x = [i for i in j if i>5]
#value of x
len(x)

#or function version
def length_of_list(list_of_numbers, number):
     x = [i for i in list_of_numbers if j > number]
     return len(x)
length_of_list(j, 5)
Run Code Online (Sandbox Code Playgroud)

有没有更浓缩的版本?

sen*_*rle 120

你可以这样做:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
Run Code Online (Sandbox Code Playgroud)

添加TrueTrue这种方式可能最初看起来很奇怪,但我认为它不是单声道的; 毕竟,bool 是一个子类int在2.3以来所有版本:

>>> issubclass(bool, int)
True
Run Code Online (Sandbox Code Playgroud)

  • `sum(如果i> 5,则为j中的i)将更加明确,如果有意的话:)`sum(1 for for if ...)`也可以隐藏在`` count`功能. (6认同)

Gre*_*ill 14

您可以创建一个较小的中间结果,如下所示:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> len([1 for i in j if i > 5])
3
Run Code Online (Sandbox Code Playgroud)

  • 或者`sum(如果i> 5,则为i中的i),这样您就不必将列表加载到内存中. (9认同)

lud*_*ics 9

如果你正在使用numpy,你可以保存一些笔画,但我不认为它比senderle的答案更快/更紧凑.

import numpy as np
j = np.array(j)
sum(j > i)
Run Code Online (Sandbox Code Playgroud)