Python 计算具有匹配属性的对象列表中的元素 [英] Python Count Elements in a List of Objects with Matching Attributes

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

问题描述

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

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

现在计算这个列表中根据属性匹配参数的对象数量的最简单函数是什么?例如,为 Person.Gender == "F" 或 Person.Age <返回 220.

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天全站免登陆