简体   繁体   English

Python:用于汇总满足条件的列表中的元素的一个班轮

[英]Python: One liner for summing up elements in a list meeting a condition

How can I write this code python in one line? 如何在一行中编写此代码python?

num_positive_weights = 0
for i in  weights['value']:
    if i >= 0:
        num_positive_weights+=1

好吧,那不是有效的Python代码(不支持i++语法),但它如下:

num_positive_weights = sum(i>=0 for i in weights['value'])
num_positive_weights = len([i for i in weights['value'] if i >= 0])
num_positive_weights = sum(filter(lambda x: x >= 0, weights['value']))

If we ignore import statements, you can write it as 如果我们忽略import语句,你可以把它写成

import operator
num_positive_weights = reduce(operator.add, (1 for i in weights['value'] if i >= 0))

If import statements count, you can do 如果import语句计数,则可以执行

num_positive_weights = reduce(__import__("operator").add, (1 for i in weights['value'] if i >= 0))

or 要么

num_positive_weights = reduce(lambda a,b: a+b, (1 for i in weights['value'] if i >= 0))

Or, to go deeper: 或者,更深入:

num_positive_weights = reduce(lambda a,b: a+1, filter(lambda i: i >= 0, weights['value']), 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM