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或者复杂的类实例,变得更为直观和安全。

相关推荐
WJX_KOI2 小时前
Open Notebook 一个开源的结合AI的记笔记软件
python
喜欢吃燃面3 小时前
Linux:环境变量
linux·开发语言·学习
0思必得03 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
徐徐同学3 小时前
cpolar为IT-Tools 解锁公网访问,远程开发再也不卡壳
java·开发语言·分布式
LawrenceLan3 小时前
Flutter 零基础入门(二十六):StatefulWidget 与状态更新 setState
开发语言·前端·flutter·dart
2301_822382763 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
m0_748229993 小时前
Laravel8.X核心功能全解析
开发语言·数据库·php
喵手4 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
qq_192779874 小时前
C++模块化编程指南
开发语言·c++·算法
2301_790300964 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python