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

时间:2016-04-03 05:39:18

标签: python

如何在一行中编写此代码python?

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

4 个答案:

答案 0 :(得分:5)

嗯,这不是有效的Python代码(i++语法不受支持),但它如下:

num_positive_weights = sum(i>=0 for i in weights['value'])

答案 1 :(得分:3)

num_positive_weights = len([i for i in weights['value'] if i >= 0])

答案 2 :(得分:1)

num_positive_weights = sum(filter(lambda x: x >= 0, weights['value']))

答案 3 :(得分:0)

如果我们忽略import语句,您可以将其写为

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

如果import语句计数,则可以

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

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

或者,更进一步:

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