Reputation: 26622
Let's say I have a list of MyClass
. I want to count the number of elements which have MyClass.SomeProperty
set to True
(assuming SomeProperty
is a boolean which is always True
or False
). My concerns are:
I know I can do:
count = len([e for e in MyList if e.SomeProperty]) # For non booleans, something like e.SomeProperty == MyValue
But it seems inefficient.
e for e
?Is it possible to do better?
Upvotes: 3
Views: 71
Reputation: 4037
Similar to the others but slightly more Pythonic imho:
sum(1 for e in MyList if e.SomeProperty)
Or if you don't care about being lazy:
len([e for e in MyList if e.SomeProperty])
Upvotes: 0
Reputation: 64368
You can use sum
with a generator expression.
count = sum( e.SomeProperty for e in MyList )
Or for a general predicate p
:
count = sum( p(e) for e in MyList )
This makes use of the fact True and False can be used as the integers 1 and 0, and the fact a generator is used will prevent a new list from being created.
If you insist on avoiding the for e in
part, you can use map
and attrgetter
:
import opertor
count = sum(map(operator.attrgetter('SomeProperty'), MyList))
Or for a general predicate p
:
count = sum(map(p, MyList))
However, this is less pythonic. I'd recommend the first approach.
Upvotes: 4