Python:一行代码实现对满足条件的列表元素求和

5
我该如何用一行Python代码来编写这段代码?
num_positive_weights = 0
for i in  weights['value']:
    if i >= 0:
        num_positive_weights+=1
4个回答

7

好的,这并不是有效的 Python 代码(不支持 i++ 语法),但正确的写法如下:

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

请注意,Python 2.x 不保证返回 1 表示 True - Selcuk
1
@Selcuk - 这是非常正确的,但在这里并不相关,因为我只是使用比较本身而不是True。 (参考链接:https://dev59.com/y3E85IYBdhLWcg3wdDSz) - TigerhawkT3

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

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

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接