Python Count Elements in a List of Objects with Matching Attributes

后端 未结 5 662
谎友^
谎友^ 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条回答
  •  旧时难觅i
    2021-02-01 13:36

    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.

提交回复
热议问题