Skip to main content
 首页 » 编程设计

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

2025年05月04日16yyy_WW

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

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

请您参考如下方法:

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