Python Count Elements in a List of Objects with Matching Attributes

后端 未结 5 609
谎友^
谎友^ 2021-02-01 13:03

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,         


        
5条回答
  •  被撕碎了的回忆
    2021-02-01 13:31

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

提交回复
热议问题