您可以在python的切换情况下使用变量吗?

问题描述 投票:0回答:2

我可以在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")

我的问题是这个:

我想获取数字范围和返回码。

python switch-statement
2个回答
0
投票
也许您正在谈论两个不同的东西:一些超出范围的值,然后是1-12的范围内的值:

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)


0
投票
Range as dictionary key in Python获得答案

如果希望将值的范围用作字典的键,请尝试此操作

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)] )

© www.soinside.com 2019 - 2024. All rights reserved.