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
  • 35,289
  • 20
  • 120
  • 115
Retr0spect
  • 187
  • 1
  • 13

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
  • 48,464
  • 6
  • 60
  • 97
  • 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,821
  • 17
  • 36
1
num_positive_weights = sum(filter(lambda x: x >= 0, weights['value']))
Quazi Marufur Rahman
  • 2,603
  • 5
  • 33
  • 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
  • 6,330
  • 3
  • 35
  • 52