【Python】用Python实现switch case语句

方式一

Python 3.10版本 更新了类似其他语言的switch case结构,所以最好的方法是直接更新到python3.10,直接使用match case 语句:

C语言:
switch (expression) {
    case constant-expression :
       statement(s);
       break; /* 可选的 */
    case constant-expression :
       statement(s);
       break; /* 可选的 */
    /* 您可以有任意数量的 case 语句 */
    default : /* 可选的 */
       statement(s);
}
Python:
flag = False
match (100, 200):
   case (100, 300):  # Mismatch: 200 != 300
       print('Case 1')
   case (100, 200) if flag:  # Successful match, but guard fails
       print('Case 2')
   case (100, y):  # Matches and binds y to 200
       print(f'Case 3, y: {y}')
   case _:  # Pattern not attempted
       print('Case 4, I match anything!')
#PEP 634: Structural Pattern Matching
match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

更详细的介绍:
https://blog.csdn.net/Datapad/article/details/123205558

方式二

使用函数实现类似switch case的效果:

def switch_case(value):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
     
    return switcher.get(value, 'wrong value')

使用匿名函数方式实现:

def foo(var,x):
	return {
			'a': lambda x: x+1,
			'b': lambda x: x+2,
			'c': lambda x: x+3,	
	}[var](x)

方式三

自定义switch case类:

# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
	def __init__(self, value):
    	self.value = value
    	self.fall = False

	def __iter__(self):
    	"""Return the match method once, then stop"""
    	yield self.match
    	raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False


# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = 'ten'
for case in switch(v):
    if case('one'):
        print 1
        break
    if case('two'):
        print 2
        break
    if case('ten'):
        print 10
        break
    if case('eleven'):
        print 11
        break
    if case(): # default, could also just omit condition or 'if True'
        print "something else!"
        # No need to break here, it'll stop anyway

# break is used here to look as much like the real thing as possible, but
# elif is generally just as good and more concise.

# Empty suites are considered syntax errors, so intentional fall-throughs
# should contain 'pass'
c = 'z'
for case in switch(c):
    if case('a'): pass # only necessary if the rest of the suite is empty
    if case('b'): pass
    # ...
    if case('y'): pass
    if case('z'):
        print "c is lowercase!"
        break
    if case('A'): pass
    # ...
    if case('Z'):
        print "c is uppercase!"
        break
    if case(): # default
        print "I dunno what c was!"

# As suggested by Pierre Quentel, you can even expand upon the
# functionality of the classic 'case' statement by matching multiple
# cases in a single shot. This greatly benefits operations such as the
# uppercase/lowercase example above:
import string
c = 'A'
for case in switch(c):
    if case(*string.lowercase): # note the * for unpacking as arguments
        print "c is lowercase!"
        break
    if case(*string.uppercase):
        print "c is uppercase!"
        break
    if case('!', '?', '.'): # normal argument passing style also applies
        print "c is a sentence terminator!"
        break
    if case(): # default
        print "I dunno what c was!"

# Since Pierre's suggestion is backward-compatible with the original recipe,
# I have made the necessary modification to allow for the above usage.

参考:https://www.cnblogs.com/gerrydeng/p/7191927.html

  • 10
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
Python中没有内置的switch/case语句。与Java、C/C++等语言不同,Python中没有直接提供switch/case语句的功能。但是,我们可以通过几种方法来实现类似功能的结构。 第一种方法是使用if...elif...elif...else语句实现类似switch/case的功能。将需要判断的条件依次放在if和elif语句中,根据条件执行相应的代码块。最后,可以使用else语句来处理默认情况。虽然这种方法比较简单,但是当分支较多或需要频繁修改时可能不够方便和易于维护。 第二种方法是使用字典来实现类似switch/case的功能。可以将不同的条件作为字典的键,对应的代码块作为字典的值。然后,可以通过检索字典来执行相应的代码块。这种方法非常灵活,可以在运行时方便地添加或删除switch/case选项。 第三种方法是在类中使用调度方法来实现类似switch/case的功能。可以将不同的条件作为方法的参数,根据不同的条件执行相应的方法体。这种方法适用于需要在类中多次使用相同的条件判断。 综上所述,尽管Python中没有直接提供switch/case语句,但可以使用if...elif...elif...else语句、字典或调度方法来实现类似的功能。具体选择哪种方法取决于你的需求和代码结构。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python switch/case语句实现方法](https://blog.csdn.net/l460133921/article/details/74892476)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AiFool

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值