python - 如何用例如使用字典的代码替换大型 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]]
解决方案
您是否有理由不能仅使用 2d 数组通过索引A
和返回颜色B
?
cols = [
['red', 'orange', 'purple'],
['orange', 'yellow', 'green' ],
['purple', 'green', 'blue' ]
]
然后它可以被称为cols[A][B]
我刚刚看到 eemz 的另一个答案,并意识到二维数组可能会变得更加复杂和重复,并有更多的颜色/选项。
推荐阅读
- node.js - 如何以角度设置图表数据,该数据取自存储在 mongodb 中并显示在 html 页面上的后端 nodejs api
- azure - 在模板中读取时,Azure 管道中设置的变量会损坏
- python - 如何使用 Python 在 mysql 中提供用户 ID
- python - 如何使用 pycryptodome 库生成一对密钥,而不会搞砸一切?
- amazon-web-services - 无法通过 https 与 AWS EC2 上的 API 托管通信
- javascript - Fullcalendar v5 Jquery 重复问题
- android - 不带空值的 Gson 转换器
- maven - 解决获取依赖项的错误:无法读取 - org.apache.http.client.HttpResponseException 的工件描述符:永久重定向 (308)
- svelte - 禁用清除 svelte 中未使用的 CSS
- react-native - React Native 为数据创建文件夹