【问题标题】:How to replace a large if-elif statement by, for example, code using a dictionary?如何用例如使用字典的代码替换大型 if-elif 语句?
【发布时间】:2021-03-02 21:07:19
【问题描述】:

我已经用 Python 编写了以下代码,但编码风格看起来很糟糕,我想用更好的东西替换它:

if A == 0 and B == 0:
    color = 'red'
elif A == 1 and B == 1:
    color = 'yellow'
elif A == 2 and B == 2:
    color = 'blue'            
elif A == 0 and B == 1:
    color = 'orange'
elif A == 1 and B == 0:
    color = 'orange'       
elif A == 2 and B == 1:
    color = 'green'
elif A == 1 and B == 2:
    color = 'green'
elif A == 0 and B == 2:
    color = 'purple'
elif A == 2 and B == 0:
    color = 'purple'  
        

我建议使用我在下面写的字典,但我很难找到如何在 Python 中编写代码,因为每个键都有多个值。

    color_dict = {
     "red": [[0,0]],
     "orange": [[0,1], [1,0]],
     "yellow": [[1,1]],
     "green": [[1,2],[2,1]],
     "blue": [[2,2]],        
     "purple": [[2,0],[0,2]]

【问题讨论】:

    标签: python dictionary if-statement


    【解决方案1】:

    您是否有理由不能只使用二维数组通过索引A 和B 来返回颜色?

    cols = [
        ['red',    'orange', 'purple'],
        ['orange', 'yellow', 'green' ],
        ['purple', 'green',  'blue'  ]
    ]
    

    然后它可以被称为cols[A][B]

    我刚刚看到 eemz 的另一个答案,并意识到二维数组可能会随着更多颜色/选项而变得更加复杂和重复。

    【讨论】:

    • 如果索引是整数 0123 等,这比我的解决方案更好
    【解决方案2】:

    你可以使用一个字典,其中的键是 (A, B) 的元组

    color = {
        (0, 0): “red”,
        (1, 1): “yellow”,
        (2, 2): “blue”,
        etc etc
    }
    result = color[(a, b)]
    

    【讨论】:

      【解决方案3】:

      也许你的意思是这个

      它不如 if-else 块高效,但它可以为您节省大量打字时间。还要注意与in 运算符的模式匹配。它可能没有你想象的那么强大。

      def find_color(a, b):
          color_dict = {
              '0,0': 'red',
              '1,1': 'yellow',
              '2,2': 'blue',
              '0,1;1,0': 'orange',
              '2,1;1,2': 'green',
              '2,0;0,2': 'purple' 
          }
          maybe_key = list(filter(lambda key: f"{a},{b}" in key, color_dict.keys()))
          return color_dict[maybe_key[0]] if maybe_key else "NotFound" 
      
      print(find_color(1, 2)) # green
      print(find_color(2, 2)) # blue
      print(find_color(3, 3)) # NotFound
      

      【讨论】:

        【解决方案4】:

        感谢您的反馈!我现在正在使用二维数组解决方案:

         A = 1
         B = 1
         cols = [
            ['red',    'orange', 'purple'],
            ['orange', 'yellow', 'green' ],
            ['purple', 'green',  'blue'  ]
         ] 
         color = colors_array[A][B]
        

        【讨论】:

          猜你喜欢
          • 2020-11-19
          • 2015-09-14
          • 2021-11-14
          • 1970-01-01
          • 1970-01-01
          • 2022-11-23
          • 2022-01-11
          • 1970-01-01
          • 2014-06-05
          相关资源
          最近更新 更多