如何避免 If 语句的围墙?

MBe*_*Bee 0 python if-statement python-3.x

我多次听说这样的编码不是最理想的:

if weapon == "sword":
 print("Knight") 
elif weapon == "katana":
 print("Samurai") 
elif weapon == "axe":
 print("Viking")
Run Code Online (Sandbox Code Playgroud)

如何以最佳方式编写此类代码?

azr*_*zro 5

您可以将这些关联存储在字典中

weapons_roles = {
    "sword": "Knight",
    "katana": "Samurai",
    "axe": "Viking"
}
Run Code Online (Sandbox Code Playgroud)
  1. 每当密钥不在字典中时,打印一些内容

    print(weapons_roles.get(weapon, "No role"))
    
    Run Code Online (Sandbox Code Playgroud)
  2. Print a role only if the weapon is known

    if weapon in weapons_roles:
        print(weapons_roles[weapon])
    
    Run Code Online (Sandbox Code Playgroud)