Python inline elif possible?

随声附和 提交于 2020-01-01 01:56:07

问题


'Hello ' + ('there' if name is None else name)

Is the equivalent of

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

What is the equivalent of this:

msg = 'Hello '
if name is None:
    msg += 'there'
elif name == 'Mr Anderson'
    msg += 'Neo'
else:
    msg += name

EDIT: for reference here is the code I wanted to shrink

srepr = '\'Modify '
if self.register == 'p':
    srepr += 'Pointer'
elif self.register == 'v':
    srepr += 'Value'
else
    srepr += 'Unknown'
srepr += ' By ' + str(self.delta) + '\''

回答1:


msg = "Hi " + ("there" if not name else ("Neo" if name == "Anderson" else name))

I think that's pretty unreadable, though.




回答2:


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.




回答3:


Do not do it.

Do this instead:

% python -m this | sed 's/^R.*/======>&<======/'

EDIT: For reference, here is how I would refactor this code...

Whenever I see elif, I think dict.

#!/usr/bin/env python

class Shrink(object):
    types = {
            'p': 'Pointer',
            'v': 'Value',
            }

    def shrink_this(self):
        return "'Modify %s By %s'" % (
                self.types.get(self.register, 'Unknown'), self.delta)

import unittest
class TestShrink(unittest.TestCase):

    def test_p(self):
        s = Shrink();
        s.register = 'p'
        s.delta = 'delta'
        self.assertEquals("'Modify Pointer By delta'", s.shrink_this())

    def test_u(self):
        s = Shrink();
        s.register = 'u'
        s.delta = 'echo'
        self.assertEquals("'Modify Unknown By echo'", s.shrink_this())

    def test_v(self):
        s = Shrink();
        s.register = 'v'
        s.delta = 'foxtrot'
        self.assertEquals("'Modify Value By foxtrot'", s.shrink_this())

if __name__ == '__main__':
    unittest.main()

Were you to need to add r for reference or pp for pointer-to-pointer, only types requires a change and your code remains readable.

Readability counts.




回答4:


'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.




回答5:


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.




回答6:


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.




回答7:


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'


来源:https://stackoverflow.com/questions/4614179/python-inline-elif-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!