Python 计算具有匹配属性的对象列表中的元素

标签 python list object attributes count

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

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。

最佳答案

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

关于Python 计算具有匹配属性的对象列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16455777/

相关文章:

python - 属性错误: 'Word2Vec' object has no attribute 'endswith'

python - R中大文件的数据格式是什么?

python idle 2.7.9 给出了错误的语法错误

c++ - 无法分配一个指向模板化类的指针的成员

java - 在 Java 中按属性值对对象 ArrayList 进行排序

javascript对象方法无法分配ajax调用响应

python - 如何将 dict 打印为 pandas.Series

python - 通过标识而不是相等从 python 列表中删除元素

python - 删除列表中的列表

java - 通过 Spring Batch 作业步骤维护作业前对象