简体   繁体   中英

using else in inline conditional python

I know I can do this:

z = a if switch == 1 else z = b

but what if I want z=a if switch=1, z=b if switch=2, and z=c if switch=3 ? Is there a python valid way to write this as a single line?

something like:

z = a if switch == 1 else z = b if switch == 2 else z = c

Thanks, just learning Python now (obviously).

Like this:

z = a if switch == 1 else (b if switch == 2 else c)

And you can keep going, but you didn't say what to use after c if it wasn't 3...

if a , b , c , ... are static, then you might as well just use a dict :

lookup = {1: a, 2: b, 3: c}
z = lookup[switch]

It'd probably be most efficient if you could generate dict only once and reuse it every time. Also note that since switch seems to be sequential integers starting at 1, you could also use a list (or tuple ):

lookup = (a, b, c)
z = lookup[switch - 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM