1

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
Ollie
  • 544
  • 4
  • 22

2 Answers2

5

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?

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • If you feel uncomfortable implicitly using the fact that `True == 1` and `False == 0`, you can make this fact explicit by doing `int(n == fresh)`. This is only useful to make the code more obvious... the language doesn't care. – SethMMorton Oct 14 '13 at 19:52
  • Sure, but there is also the line [Explicit is better than implicit](http://www.python.org/dev/peps/pep-0020/). I personally don't care, but it was in case the OP has a gut reaction against implicitly using `bool`s as `int`s. To be clear, I'm not saying you are wrong... my comment was an addendum intended for the OP in case they wanted to make a more self-documenting code. – SethMMorton Oct 14 '13 at 19:59
1

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)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525