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
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?
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)