python idiomatische Python for-Schleife if else-Anweisung
Wie kann ich @ verwendelse
Anweisung in einem idiomatischen Pythonfor
loop? Ohneelse
Ich kann z.B. schreiben
res = [i for i in [1,2,3,4,5] if i < 4]
Das Ergebnis ist:[1, 2, 3]
Die normale Form des obigen Codes ist:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
Das Ergebnis ist dasselbe wie in idiomatischer Form:[1, 2, 3]
Und ich will das:
res = [i for i in [1,2,3,4,5] if i < 4 else 0]
Ich bekommeSyntaxError: invalid syntax
. Das Ergebnis sollte lauten:[1, 2, 3, 0, 0]
Der normale Code hierfür ist:
res = []
for i in [1,2,3,4,5]:
if i < 4:
res.append(i)
else:
res.append(0)
Das Ergebnis ist:[1, 2, 3, 0, 0]