Python Count Elements in a List of Objects with Matching Attributes

后端 未结 5 610
谎友^
谎友^ 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:22

    I found that using a list comprehension and getting its length was faster than using sum().

    According to my tests...

    len([p for p in PeopleList if p.Gender == 'F'])
    

    ...runs 1.59 times as fast as...

    sum(p.Gender == "F" for p in PeopleList)
    

提交回复
热议问题