[英]How can I count occurrences of elements that are bigger than a given number in an list?
Let's say I have this list: 假设我有这个清单:
a = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1]
I want to know how many elements are there bigger than 7. The result should be 3
. 我想知道有多少元素大于7.结果应该是
3
。 Is there an elegant way to do this in Python? 在Python中有一种优雅的方法吗? I tried with
count
but it won't work. 我尝试了
count
但它不起作用。
更短,使用numpy:
sum(np.array(a)>7)
write a function that return you count of elements greater than specific number. 编写一个函数,返回大于特定数字的元素数。
def get_max_count(l, num):
count = 0
for x in l:
if x > num:
count+=1
return count
l = [1.1, 2, 3.1, 4, 5, 6, 7.2, 8.5, 9.1]
print get_max_count(l=l, num = 7)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.