+ 2
List comprehension if-else in one line
I'm shortening a code and trying to compress an if/else statement but I don't how to. This is what I have If opcn1 == 1: var1 = X Elif opcn1 == 2: Var1 = Y Elif opcn1 == 3: Var1 = Z Elif opcn1 == n... etc...
2 Antworten
+ 3
You can try this :))
var1 = X if opcn1 == 1 else Y if opcn1 == 2 else Z if opcn1 == 3 else ....
Example :
x = 1
y = 'one' if x == 1 else 'two' if x == 2 else 'idk'
print(y) # one
0
You can use a tuple:
Var1 = (None, X, Y, Z)[opcn1]
https://code.sololearn.com/cKcgEYDfJ5Wi/?ref=app