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
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
Well, that's not valid Python code (the i++
syntax isn't supported), but it would be as follows:
num_positive_weights = sum(i>=0 for i in weights['value'])
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)