Wie kann ich else
Anweisung in einem idiomatischen Python for
Schleife verwenden? Ohne else
kann ich zB schreiben:Python idiomatische Python für Schleife wenn sonst Anweisung
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 das gleiche wie in idiomatische Form ist: [1, 2, 3]
Und ich möchte dies:
res = [i for i in [1,2,3,4,5] if i < 4 else 0]
Ich bekomme SyntaxError: invalid syntax
. Das Ergebnis sollte sein: [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]