Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 440
Retr0spect Avatar asked Dec 18 '22 18:12

Retr0spect


2 Answers

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'])
like image 106
TigerhawkT3 Avatar answered Dec 21 '22 11:12

TigerhawkT3


num_positive_weights = len([i for i in weights['value'] if i >= 0])
like image 40
Banach Tarski Avatar answered Dec 21 '22 10:12

Banach Tarski