简体   繁体   中英

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

How can I write this code python in one line?

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 operator
num_positive_weights = reduce(operator.add, (1 for i in weights['value'] if i >= 0))

If import statements count, you can do

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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