在对象与匹配属性列表的Python计数元素 [英] Python Count Elements in a List of Objects with Matching Attributes

查看:347
本文介绍了在对象与匹配属性列表的Python计数元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到匹配条件的名单统计对象数量的简单,快捷的方式。
例如。

 类人:
    高清__init __(自我,姓名,年龄,性别等):
        self.Name =名称
        self.Age =年龄
        self.Gender =性别人民#名单
PeopleList = [人(琼,15,F),
              人(亨利,18日,M),
              人(玛格21,F)

现在什么对于在此列表中根据其属性匹配参数是计算的对象的数量的最简单的功能?
例如,返回2 Person.Gender ==F或P​​erson.Age< 20。


解决方案

 类人:
    高清__init __(自我,姓名,年龄,性别等):
        self.Name =名称
        self.Age =年龄
        self.Gender =性别
>>> PeopleList = [人(琼,15,F),
              人(亨利,18日,M),
              人(玛格21,F)
>>>总和(p.Gender ==F代表在PeopleList p)的
2
>>>总和(;对于PeopleList第20页p.Age&LT)
2

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.

解决方案

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计数元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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