列表中值的数量大于一定数量


68

我有一个数字列表,我想获取一个数字在满足特定条件的列表中出现的次数。我可以使用列表推导(或函数中的列表推导),但我想知道是否有人有更短的方法。

# 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)

还有更精简的版本吗?

Answers:


144

您可以执行以下操作:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3

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

>>> issubclass(bool, int)
True

1
@jamylak,为什么这比Greg Hewgill更好?尽管它很有趣且正确,但是对于其他阅读代码的人来说,它似乎不那么直观,也不那么明显。
TJD 2012年

1
@TJD没说更好,但我更喜欢。
jamylak 2012年

@senderle:(Greg先前删除的答案。我添加了一个新的答案,它将起作用。:)
Greg Hewgill

6
sum(1 for i in j if i > 5)如果需要的话,它会更加明确:)sum(1 for ... if ...)也可以将其隐藏在count函数中。
Niklas B.

@NiklasB。,嗯,您当然是对的-甚至不需要条件表达式。
senderle'5

18

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

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> len([1 for i in j if i > 5])
3

10
sum(1 for i in j if i > 5)因此,您不必将列表加载到内存中。
jamylak'5

12

如果您另外使用numpy,则可以节省一些笔触,但是我不认为它比senderle的答案要快/紧凑。

import numpy as np
j = np.array(j)
sum(j > i)


4

如果您使用的是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“魔术”进行计时)


2

使用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

1

我将添加一个地图和过滤器版本,因为为什么不这样做。

sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))

0

您可以使用函数来做到这一点:

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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.