Superbest
Superbest

Reputation: 26622

Shortest way of counting?

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.

Is it possible to do better?

Upvotes: 3

Views: 71

Answers (3)

wouter bolsterlee
wouter bolsterlee

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

shx2
shx2

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

Daniel
Daniel

Reputation: 42778

Sure you meant:

count = sum(bool(e.SomeProperty) for e in MyList)

Upvotes: 0

Related Questions