正如标题所述,编写以下代码的pythonic方法是什么?
if x == 1:
myvar = "a string"
elif x == 2:
myvar = "another string"
elif x == 3:
myvar = "yet another string"
else:
raise Exception("arg x must be 1, 2 or 3")
执行上述操作似乎有点笨拙,而对于更长的示例,则更加耗时且混乱。
答案 0 :(得分:5)
您要为此使用字典:
x = 3 # Then try with 4
outcome_dict = {1: "some string", 2: "another string", 3: "yet another string"}
my_var = outcome_dict.get(x)
if my_var is None:
raise Exception("arg x must be 1, 2 or 3")
print(my_var)
如果找不到密钥,则dict.get()
方法将返回None
。在此示例中,所有结果都需要在outcome_dict
中手动键入,但实际上,很容易在单行代码中为数千个键:值对创建字典,例如字典理解或常规的for
循环。
答案 1 :(得分:1)
除了@roganjosh的解决方案之外,您还可以尝试使用try
和except
。
dict_values = {1: "some string", 2: "another string", 3: "yet another string"}
# Using for x = 3
x = 3
try:
print (outcome_dict[x])
except:
print ("arg x must be 1, 2 or 3")
# yet another string
# Using for x = 4
x = 4
try:
print (outcome_dict[x])
except:
print ("arg x must be 1, 2 or 3")
# arg x must be 1, 2 or 3