mardi 31 décembre 2019

Python if else condition in one line syntax

I know this question has been asked lots of times but I still cannot get the syntax right to get it to one line:

string = 'abcdea'
ab = []

for c in list(string):
    if c in ['a','b']:
        ab.append(c) 

One line (does not work):

ab.append(c) if c in ['a','b'] for c in list(string)

Aucun commentaire:

Enregistrer un commentaire