列表中值的数量大于一定数量 [英] number of values in a list greater than a certain number

查看:74
本文介绍了列表中值的数量大于一定数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of numbers and I want to get the number of times a number appears in a list that meets a certain criteria. I can use a list comprehension (or a list comprehension in a function) but I am wondering if someone has a shorter way.

# 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似乎很奇怪,但是我并不认为这很奇怪.毕竟,bool 是自2.3版以来所有版本中int的子类:

It might initially seem strange to add True to True this way, but I don't think it's unpythonic; after all, bool is a subclass of int in all versions since 2.3:

>>> issubclass(bool, int)
True

这篇关于列表中值的数量大于一定数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆