计算满足Python条件的所有条件

时间:2013-10-14 19:46:20

标签: python loops

有没有办法在速记嵌套循环中添加满足条件的所有内容?我的以下尝试没有成功:

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

2 个答案:

答案 0 :(得分:5)

sum与生成器表达式一起使用:

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

True == 1False == 0,因此不需要else


相关内容: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?

答案 1 :(得分:1)

使用sum()功能:

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

或:

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