57

我试图找到一种简单快速的方法来计算列表中符合条件的对象数量。例如

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 == "F" 或 Person.Age < 20 返回 2。

4

5 回答 5

77
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
于 2013-05-09T06:32:17.310 回答
13

我知道这是一个老问题,但现在一种 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']
于 2016-11-24T15:17:51.710 回答
8

我发现使用列表推导并获取其长度比使用sum().

根据我的测试...

len([p for p in PeopleList if p.Gender == 'F'])

...运行速度是...的 1.59 倍

sum(p.Gender == "F" for p in PeopleList)
于 2015-07-17T18:08:38.230 回答
3

我更喜欢这个:

def count(iterable):
    return sum(1 for _ in iterable)

然后你可以像这样使用它:

femaleCount = count(p for p in PeopleList if p.Gender == "F")

这很便宜(不会创建无用的列表等)并且完全可读(我会说比两者都好) sum(1 for … if …)and sum(p.Gender == "F" for …))。

于 2015-05-22T09:32:48.270 回答
2

就我个人而言,我认为定义一个函数在多种用途上更简单:

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

特别是如果您想重用查询。

于 2013-05-09T07:02:19.997 回答