Python 计算具有匹配属性的对象列表中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16455777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Count Elements in a List of Objects with Matching Attributes
提问by FacesOfMu
I am trying to find a simple and fast way of counting the number of Objects in a list that match a criteria. 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")]
Now what's the simplest function for counting the number of objects in this list that match an argument based on their attributes? E.g., returning 2 for Person.Gender == "F" or Person.Age < 20.
现在,用于计算此列表中根据属性与参数匹配的对象数量的最简单函数是什么?例如,为 Person.Gender == "F" 或 Person.Age < 20 返回 2。
采纳答案by jamylak
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
回答by kampu
Personally I think that defining a function is more simple over multiple uses:
我个人认为定义一个函数比多次使用更简单:
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))
Particularly if you want to reuse a query.
特别是如果您想重用查询。
回答by Alfe
I prefer this:
我更喜欢这个:
def count(iterable):
return sum(1 for _ in iterable)
Then you can use it like this:
然后你可以像这样使用它:
femaleCount = count(p for p in PeopleList if p.Gender == "F")
which is cheap (doesn't create useless lists etc) and perfectly readable (I'd say better than both sum(1 for … if …)and sum(p.Gender == "F" for …)).
它很便宜(不会创建无用的列表等)并且完全可读(我会说比sum(1 for … if …)和更好sum(p.Gender == "F" for …))。
回答by Webucator
回答by lonetwin
I know this is an old question but these days one stdlib way to do this would be
我知道这是一个老问题,但现在一种标准库方法是
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']

