有没有办法在速记嵌套循环中添加满足条件的所有内容?我的以下尝试没有成功:
count += 1 if n == fresh for n in buckets['actual'][e] else 0
答案 0 :(得分:5)
将sum
与生成器表达式一起使用:
sum(n == fresh for n in buckets['actual'][e])
为True == 1
和False == 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)