Python inline elif possible?

前端 未结 7 2256
耶瑟儿~
耶瑟儿~ 2021-02-07 11:16
\'Hello \' + (\'there\' if name is None else name)

Is the equivalent of

msg = \'Hello \'
if name is None:
    msg += \'there\'
else:
          


        
相关标签:
7条回答
  • 2021-02-07 11:52

    Firstly, run 'pip install pyswitch'

    Then:

    import pyswitch
    
    mySwitch = pyswitch.Switch()
    
    @mySwitch.case(None):
    def gotNone(value):
        return 'Hello there'
    
    @mySwitch.case('Mr. Anderson')
    def gotMrAnderson(value):
        return 'Hello Neo'
    
    @mySwitch.default
    def gotDefault(value):
        return 'Hello %s' % value
    
    msg = mySwitch.switch(None)  # Returns 'Hello there'
    msg = mySwitch.switch('Mr. Anderson')  # Returns 'Hello Neo'
    msg = mySwitch.switch('OoglyMoogly')  # Returns 'Hello OoglyMoogly'
    
    0 讨论(0)
  • 2021-02-07 11:57

    Use a dictionary to perform a mapping:

    srepr = "'Modify " + {"p": "Pointer", "v": "value"}.get(self.register, "Unknown")
    

    (by the way, instead of '\'...' you can use "'... for a bit more clarity.

    0 讨论(0)
  • 2021-02-07 11:57
    'Hello ' + \
    ('there' if name is None else \
        'Neo' if name == 'Mr Anderson' else \
        name)
    

    I recommend against this; if your conditions become this complex, stick it in a function.

    0 讨论(0)
  • 2021-02-07 12:10
    msg = "Hi " + ("there" if not name else ("Neo" if name == "Anderson" else name))
    

    I think that's pretty unreadable, though.

    0 讨论(0)
  • 2021-02-07 12:13

    You could also do this:

    msg= 'Hello ' + {name is None: 'there', name == 'Mr Anderson': 'Neo'}.get(True, name)
    

    So either of name is None or name == 'Mr Anderson' is True, or none of them is True, then name will be used.

    0 讨论(0)
  • 2021-02-07 12:14
    msg = 'Hello ' + (
        'there' if name is None else
        'Neo' if name == 'Mr Anderson' else
        name
    )
    

    This is a reiteration of several other answers, but with nicer formatting. I consider this most readable, and this is the approach I would use.

    0 讨论(0)
提交回复
热议问题