【问题标题】:The best way to replace multiple if-statementes with a dictionary用字典替换多个 if 语句的最佳方法
【发布时间】:2017-05-02 16:36:16
【问题描述】:

我有多种情况:

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)

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

if you == 1 or you == 2:
    one.put(argument)
elif you == 3:
    return None

最好的方法是什么?

【问题讨论】:

  • 你应该在codereview.stackexchange.com上问这个
  • 有什么例外?
  • 也许吧,但我正在学习。我还不是专业的开发人员
  • @DeepSpace 从第一行到第四行。不一样,我们在第四行之后使用
  • 所以我写了一篇关于过去使用python字典而不是if-else语句的博客。你可以阅读它here

标签: python python-3.x for-loop if-statement


【解决方案1】:

将表达式的不同部分存储在字典中。 我也把 3 放在那里,只是为了完整性,以备日后使用。

put_dict = {
    1: one, 2: one,
    3: None
    4: two,  5: three,
    6: four, 7: five,
    8: six,  9: seven,
    10: eight, 11: nine,
    12: ten
}

if you == 3:
    return None
else:
    put_dict[you].put(argument)  

【讨论】:

    【解决方案2】:

    这将起作用:

    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
    

    【讨论】:

      【解决方案3】:

      我会为你不想要的值创建一个接收器:

      class Sink:
          @staticmethod
          def put(object):
              pass
      
      put_dict = {
          1: one, 2: one,
          3: Sink,
          4: two,  5: three,
          6: four, 7: five,
          8: six,  9: seven,
          10: eight, 11: nine,
          12: ten}
      
      def function(you, argument)
          put_dict[you].put(argument)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 2016-09-23
        • 2012-02-10
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        相关资源
        最近更新 更多