我可以在python 3上编码时使用此方法吗?
def switch_demo(argument):
switcher = {
51>switcher>13: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
90>switcher>52: "December"
}
print switcher.get(argument, "Invalid month")
我的问题是这个:
我想获取数字范围和返回码。
def switch_demo(argument):
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December"
}
return switcher.get(argument, "Invalid month")
def switch_range(argument):
if argument <= 12:
return switch_demo(argument)
elif argument <= 51:
return switch_demo(1)
else:
return switch_demo(12)
如果希望将值的范围用作字典的键,请尝试此操作
switcher = dict(
[(n, 'January')
for n in range(13,51)] +
[(2, 'February')] +
[(3, 'March')] +
[(4, 'April')] +
[(5, 'May')] +
[(6, 'June')] +
[(7, 'July')] +
[(8, 'August')] +
[(9, 'September')] +
[(10, 'October')] +
[(11, 'November')] +
[(n, 'December')
for n in range(52,90)]
)