我试图找到一种简单快速的方法来计算列表中符合条件的对象数量。 e.g。
class Person:
def __init__(self, Name, Age, Gender):
self.Name = Name
self.Age = Age
self.Gender = Gender
# List of People
PeopleList = [Person("Joan", 15, "F"),
Person("Henry", 18, "M"),
Person("Marg", 21, "F")]
现在,计算此列表中与基于其属性的参数匹配的对象数量的最简单函数是什么? 例如,为Person.Gender返回2 =“F”或Person.Age< 20。
答案 0 :(得分:41)
class Person:
def __init__(self, Name, Age, Gender):
self.Name = Name
self.Age = Age
self.Gender = Gender
>>> PeopleList = [Person("Joan", 15, "F"),
Person("Henry", 18, "M"),
Person("Marg", 21, "F")]
>>> sum(p.Gender == "F" for p in PeopleList)
2
>>> sum(p.Age < 20 for p in PeopleList)
2
答案 1 :(得分:11)
我知道这是一个老问题,但是现在有一种stdlib方法可以做到这一点
from collections import Counter
c = Counter(getattr(person, 'gender') for person in PeopleList)
# c now is a map of attribute values to counts -- eg: c['F']
答案 2 :(得分:5)
我发现使用列表推导并获得其长度比使用sum()
更快。
根据my tests ...
len([p for p in PeopleList if p.Gender == 'F'])
...的运行速度是......的1.59倍。
sum(p.Gender == "F" for p in PeopleList)
答案 3 :(得分:1)
我个人认为定义函数在多种用途中更简单:
def count(seq, pred):
return sum(1 for v in seq if pred(v))
print(count(PeopleList, lambda p: p.Gender == "F"))
print(count(PeopleList, lambda p: p.Age < 20))
特别是如果您想重用查询。
答案 4 :(得分:0)
我更喜欢这个:
def count(iterable):
return sum(1 for _ in iterable)
然后你可以像这样使用它:
femaleCount = count(p for p in PeopleList if p.Gender == "F")
哪个便宜(没有创建无用的列表等)并且完全可读(我说比sum(1 for … if …)
和sum(p.Gender == "F" for …)
更好。)