简体   繁体   English

如何计算列表中大于给定数字的元素的出现次数?

[英]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但它不起作用。

>>> a = [1.1 , 2 , 3.1 , 4 , 5 , 6 , 7.2 , 8.5 , 9.1]
>>> sum(x > 7 for x in a)
3

This uses the fact that bool s are int s too. 这使用了bool s也是int的事实。

(If you oppose this because you think it isn't clear or pythonic then read this link ) (如果你反对这个,因为你认为它不清楚或pythonic然后阅读此链接

更短,使用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.

相关问题 如何计算嵌套列表中多个交叉点的出现次数 - How can I count the number of occurrences of multiple intersections in a nested list 如何快速计算从字典列表中分配给列总和的元素数量? - How can I count the number of elements given to a column sum from a list of dictionaries quickly? 计算(排序的)列表中给定项目的出现次数? - Count the number of occurrences of a given item in a (sorted) list? 如何有效地计算给定字符在字符串的一定范围内出现的次数? - How can I efficiently count the number of occurrences of a given character within certain range of a string? 有没有更快的方法可以计算列表中某个数字的出现次数? - Is there a faster way I can count the number of occurrences of a number in a list? 给定一个项目,如何计算该项目在列表中的出现次数,如果不符合某些规定,则不打印该项目? - Given an item, how can I count the occurrences of said item in a list, and not print the item if it does not reach certain regulations? 计算给定整数列表在另一整数列表中出现的总数 - Count total number of occurrences of given list of integers in another 计算数据流中给定字符串列表的出现次数 - Count number of occurrences of a given list of strings in a data stream Python-如何计算列表中的出现次数 - Python - How to count the number of occurrences in a list 如何计算列表中“None”的出现次数? - How to count the number of occurrences of `None` in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM