5

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
Serenity
  • 32,301
  • 18
  • 107
  • 109
Retr0spect
  • 187
  • 1
  • 12

4 Answers4

7

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'])
TigerhawkT3
  • 46,954
  • 6
  • 53
  • 87
  • Please note that it is _not guaranteed_ for Python 2.x to return `1` for `True`. – Selcuk Apr 03 '16 at 05:44
  • 1
    @Selcuk - That's very true, but not relevant here, as I'm simply using [the comparison itself rather than `True`](http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante). – TigerhawkT3 Apr 03 '16 at 05:57
4
num_positive_weights = len([i for i in weights['value'] if i >= 0])
Banach Tarski
  • 1,801
  • 14
  • 35
1
num_positive_weights = sum(filter(lambda x: x >= 0, weights['value']))
Quazi Marufur Rahman
  • 2,543
  • 4
  • 31
  • 51
0

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)
RoadieRich
  • 5,983
  • 3
  • 37
  • 51