我有一个数字列表,我想得到一个数字出现在符合特定条件的列表中的次数.我可以使用列表理解(或函数中的列表理解),但我想知道是否有人有更短的方式.
# 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)
添加True
到True
这种方式可能最初看起来很奇怪,但我认为它不是单声道的; 毕竟,bool
是一个子类的int
在2.3以来所有版本:
>>> issubclass(bool, int)
True
Run Code Online (Sandbox Code Playgroud)
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)
如果你正在使用numpy,你可以保存一些笔画,但我不认为它比senderle的答案更快/更紧凑.
import numpy as np
j = np.array(j)
sum(j > i)
Run Code Online (Sandbox Code Playgroud)