首页 > 解决方案 > 如何用例如使用字典的代码替换大型 if-elif 语句?

问题描述

我用 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]]

标签: pythondictionaryif-statement

解决方案


您是否有理由不能仅使用 2d 数组通过索引A和返回颜色B

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

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

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


推荐阅读