Dict Magic
if-elif-else Kaskade
Altes Problem, kennt man:
>>> if var == 'one':
... res = 1
... elif var == 'two':
... res = 2
... elif var == 'three':
... res = 3
... else:
... res = -1
Doch schon mal daran gedacht, das alles ein bisschen kompakter zu formulieren?
>>> res = dict(
... one=1,
... two=2,
... three=3,
... ).get(var, -1)
last update: 2024-01-28 17:42:17 +0100