我多次听说这样的编码是不理想的:if weapon == "sword": print("Knight") elif weapon == "katana": print("Samurai") elif weapon == "axe": print("Viking")如何以最佳方式编写此类代码?
2 回答

慕姐4208626
TA贡献1852条经验 获得超7个赞
您可以将这些关联存储在字典中
weapons_roles = {
"sword": "Knight",
"katana": "Samurai",
"axe": "Viking"
}
打印一些东西,只要钥匙不在字典中
print(weapons_roles.get(weapon, "No role"))
仅当武器已知时才打印角色
if weapon in weapons_roles:
print(weapons_roles[weapon])

心有法竹
TA贡献1866条经验 获得超5个赞
试试下面这个:
def example_function(weapon):
weapon_dict = {'sword': 'Knight', 'katana': 'Samurai', 'axe': 'Viking'}
return weapon_dict[weapon]
添加回答
举报
0/150
提交
取消