【问题标题】:Inline if-else extensionInline if-else extension
【发布时间】:2022-12-27 21:48:36
【问题描述】:

I learned on the post How to write inline if statement for print? how to do inline if-else. Examples: Given assignment a=True, it expected the output 42 for statement print(42 if a else 24) and equivalent assignment x=42 on assignment x = (42 if a else 24).

Is there a way to use one further conditional statement i.e. 42 if a=='Hitchhicker' else if a=='Mountain-biker' 30 else 7?

【问题讨论】:

  • Did you try it?
  • 42 if a=='Hitchhicker' else 30 if a=='Mountain-biker' else 7. But if there is more options it's better to initialize dictionary d = {'Hitchhicker': 42, 'Mountain-biker': 30} and use d.get(a, 7).
  • It's not a statement but an expression, and all three parts of it can be any expression. You can go even further than (a if b else c) if (d if e else f) else (g if h else i) if you want your coworkers to dislike you.
  • Why do I receive "-1" votes? This is very annoying, community!

标签: python


【解决方案1】:

You can do this:

42 if a=='Hitchhicker' else 30 if a=='Mountain-biker' else 7

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多