我有一个数字列表,我想获取某个数字在满足特定条件的列表中出现的次数。我可以使用列表理解(或函数中的列表理解),但我想知道是否有人有更短的方法。
# 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)
有没有更精简的版本?
你可以这样做:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
以这种方式将
True
添加到 True
最初可能看起来很奇怪,但我不认为这是不符合 Python 的;毕竟,自 2.3 以来的所有版本中,bool
都是 int
的子类:
>>> issubclass(bool, int)
True
您可以像这样创建一个较小的中间结果:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> len([1 for i in j if i > 5])
3
如果你以其他方式使用numpy,你可以节省一些笔画,但我不认为它比senderle的答案更快/更紧凑。
import numpy as np
j = np.array(j)
sum(j > i)
(有点)不同的方式:
reduce(lambda acc, x: acc + (1 if x > 5 else 0), j, 0)
如果您使用 NumPy(如 ludaavic 的答案),对于大型数组,您可能需要使用 NumPy 的
sum
函数而不是 Python 的内置 sum
来显着加速 - 例如,1000 万次加速 >1000 倍我笔记本电脑上的元素数组:
>>> import numpy as np
>>> ten_million = 10 * 1000 * 1000
>>> x, y = (np.random.randn(ten_million) for _ in range(2))
>>> %timeit sum(x > y) # time Python builtin sum function
1 loops, best of 3: 24.3 s per loop
>>> %timeit (x > y).sum() # wow, that was really slow! time NumPy sum method
10 loops, best of 3: 18.7 ms per loop
>>> %timeit np.sum(x > y) # time NumPy sum function
10 loops, best of 3: 18.8 ms per loop
(上面使用了 IPython 的
%timeit
“魔法”来计时)
使用 bisect 模块的不同计数方式:
>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3
我将添加地图和过滤器版本,因为为什么不呢。
sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))
您可以使用函数这样做:
l = [34,56,78,2,3,5,6,8,45,6]
print ("The list : " + str(l))
def count_greater30(l):
count = 0
for i in l:
if i > 30:
count = count + 1.
return count
print("Count greater than 30 is : " + str(count)).
count_greater30(l)
这有点长,但针对初学者的详细解决方案:
from functools import reduce
from statistics import mean
two_dim_array = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
# convert two dimensional array to one dimensional array
one_dim_array = reduce(list.__add__, two_dim_array)
arithmetic_mean = mean(one_dim_array)
exceeding_count = sum(i > arithmetic_mean for i in one_dim_array)
通过
collections.Counter
过滤:
j = [4,5,6,7,1,3,7,5]
c = Counter(j)
greater_than = 2
updated = Counter({k: count for k, count in c.items() if count >= greater_than})