替换Python中的switch语句

Python doesn't provide a built-in switch statement, unlike other programming languages.

与其他编程语言不同,Python不提供内置的switch语句。

But there are scenarios, for which, using a switch statement is more optimized. To benefit ourselves to use a switch case, the following are the work-around.

但是在某些情况下,使用switch语句会得到更优化。 为了使自己受益于使用开关盒,以下是解决方法。

Consider the below example, of switch case in Java

考虑下面的例子, Java中切换案例

public static String switchCase(int monthNum) {
    String monthName = "Invalid Month";
    switch (monthNum) {
        case 1:
            monthName = "January";
            break;
        case 2:
            monthName = "February";
            break;
        case 3:
            monthName = "March";
            break;
        case 4:
            monthName = "April";
            break;
        case 5:
            monthName = "May";
            break;
        case 6:
            monthName = "June";
            break;
        case 7:
            monthName = "July";
            break;
        case 8:
            monthName = "August";
            break;
        case 9:
            monthName = "September";
            break;
        case 10:
            monthName = "October";
            break;
        case 11:
            monthName = "November";
            break;
        case 12:
            monthName = "December";
            break;
        default:
            monthName = "Please provide the month number";
    }
    return monthName;
}

Now, by using the dictionary in python, we will be able to replicate similar behavior.

现在,通过使用python中字典 ,我们将能够复制类似的行为。

def month(i):
	switch={
		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 switch.get(i, "Invalid month")

# printing
print(month(12))
print(month(13))

Output

输出量

December
Invalid month

In the above for values other than the ones mentioned in the switch, the code prints out "Invalid day of week". This is because we tell it to do so using the get() method of a dictionary.

在上面的值中,除了开关中提到的值以外,代码打印出“ Invalid day of week” 。 这是因为我们告诉它使用dictionaryget()方法这样做。

翻译自: https://www.includehelp.com/python/replacements-for-switch-statement.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值