lundi 8 janvier 2018

Python for and if-else One line syntax [duplicate]

This question already has an answer here:

I want to convert following code to one line code

pos, neg=0,0
for val in price_changes:
        if val >0:
            pos+=val
        else:
            neg+=val

Converted to

pos, neg=0,0
pos+=val if val>0 else neg+=val for val in price_changes

But it gives syntax error

SyntaxError: invalid syntax

Where I am wrong

Aucun commentaire:

Enregistrer un commentaire