[英]Count all that satisfy a condition in Python
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
与生成器表达式一起使用:
sum(n == fresh for n in buckets['actual'][e])
as True == 1
and False == 0
, so else
is not required. 因为
True == 1
和False == 0
,所以不需要else
。
Related reads: Is it Pythonic to use bools as ints? 相关阅读: 将布尔值用作整数是否为Pythonic? , Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
, Python中的False == 0和True == 1是实现细节还是由语言保证?
Using sum()
function: 使用
sum()
函数:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.