例如,如何通过使用字典的代码替换大型 if-elif 语句?

时间:2021-03-02 21:07:19

标签: python dictionary if-statement

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

4 个答案:

答案 0 :(得分:3)

是否有理由不能仅使用二维数组通过索引 AB 来返回颜色?

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

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

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

也许你的意思是这个

它不如 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

答案 3 :(得分:0)

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

{'A': 1, 'C': 1, 'D': 1}