Ollie
Ollie

Reputation: 544

Count all that satisfy a condition in Python

Is there a way to add all that satisfy a condition in a shorthand nested loop? My following attempt was unsuccessful:

count += 1 if n == fresh for n in buckets['actual'][e] else 0

Upvotes: 1

Views: 87

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

Use sum with a generator expression:

sum(n == fresh for n in buckets['actual'][e])

as True == 1 and False == 0, so else is not required.


Related reads: Is it Pythonic to use bools as ints? , Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

Upvotes: 5

Rohit Jain
Rohit Jain

Reputation: 213391

Using sum() function:

sum(1 if n == fresh else 0  for n in buckets['actual'][e])

or:

sum(1 for n in buckets['actual'][e] if n == fresh)

Upvotes: 1

Related Questions