Python中的switch

在Python 3.10中引入了一个match语句,其类似于其他语言(eg:C,JAVA)中的switchcase语句,但更为强大。下面是一个使用Python 3.10中match语句的示例:

python 复制代码
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 401 | 403 | 404:
            return "Not allowed"
        case 500:
            return "Server error"
        case _:
            return "Something's wrong with the internet"

print(http_error(400))  # 输出: Bad request
print(http_error(401))  # 输出: Not allowed
print(http_error(500))  # 输出: Server error
print(http_error(600))  # 输出: Something's wrong with the internet

在这个例子中,match语句将status参数与一系列模式进行比较。这些模式可以是单个值,如400500,或者值的组合,如401 | 403 | 404。如果没有匹配,它将匹配到通配符_

此外,match也可以用在数据结构解构上:

python 复制代码
# 假设我们有一个包含不同类型元素的列表
def handle_items(items):
    match items:
        case []:
            print("No items.")
        case [first]:
            print(f"One item: {first}")
        case [first, second]:
            print(f"Two items: {first} and {second}")
        case [first, *rest]:
            print(f"First item: {first}, rest: {rest}")

handle_items([])              # 输出: No items.
handle_items(["apple"])       # 输出: One item: apple
handle_items(["apple", "banana"]) # 输出: Two items: apple and banana
handle_items(["apple", "banana", "cherry"]) # 输出: First item: apple, rest: ['banana', 'cherry']

在这个例子中,match语句检查items列表,根据列表的长度和内容选择不同的代码块来执行。

match允许开发者写出更简洁、易读并且能直接映射到数据结构和条件的代码。这使得处理复杂的数据结构,如嵌套的JSON或者复杂的类实例,变得更为直观和安全。

相关推荐
jzlhll12311 分钟前
Kotlin 协程高级用法之 NonCancellable
android·开发语言·kotlin
结衣结衣.20 分钟前
走进机器学习:新手必看的完整入门指南
人工智能·python·学习·机器学习
我是唐青枫24 分钟前
C#.NET YARP + OpenTelemetry:网关链路追踪实战
开发语言·c#·.net
芯芯点灯26 分钟前
gd32f303烧录提示Flash Timeout. Reset the Target and try it again.;
开发语言·前端·javascript
绘梨衣54728 分钟前
某公开数据简单逆向
python·beautifulsoup
枫叶丹431 分钟前
【HarmonyOS 6.0】Enterprise Space Kit:空间管理服务深入解析
开发语言·华为·harmonyos
就叫_这个吧1 小时前
Java实现线程间的通讯--使用synchronized关键字和JUC方式实现
java·开发语言
FlyWIHTSKY1 小时前
Next中引入 Ant Design (antd)的配置
开发语言·前端·javascript
小江的记录本1 小时前
【Java并发编程】锁机制:volatile:JMM内存模型、可见性/禁止指令重排、内存屏障、单例模式中的应用(附《思维导图》+《面试高频考点清单》)
java·后端·python·mysql·单例模式·面试·职场和发展