用字典替换多个 if 语句的最佳方法

Pid*_*una 2 python for-loop if-statement python-3.x

我有一个多重条件:

if you == 1 or you == 2:
    one.put(argument)
elif you == 3:
    return None
elif you == 4:
    two.put(argument)
elif you == 5:
    three.put(argument)
elif you == 6:
    four.put(argument)
elif you == 7:
    five.put(argument)
elif you == 8:
    six.put(argument)
elif you == 9:
    seven.put(argument)
elif you == 10:
    eight.put(argument)
elif you == 11:
    nine.put(argument)
elif you == 12:
    ten.put(argument)
Run Code Online (Sandbox Code Playgroud)

我想将其更改为使用字典,但出现以下异常:

if you == 1 or you == 2:
    one.put(argument)
elif you == 3:
    return None
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

Dee*_*ace 6

这将起作用:

actions = {1: one.put,
           2: one.put,
           3: None,
           4: two.put,
           # ....
           }

action = actions.get(you)
if callable(action):  # guards against non existing "you"'s or if you == 3
    action(argument)

# can also do this:
# if action is not None:
    # action(argument)

# or that..
# try:
#     action(argument)
# except TypeError:  # if action is None we'll get an exception, NoneType isn't callable
#    pass
Run Code Online (Sandbox Code Playgroud)