Python中的switch

在Python 3.10中引入了一个match语句,其类似于其他语言(eg:C,JAVA)中的switch或case语句,但更为强大。下面是一个使用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参数与一系列模式进行比较。这些模式可以是单个值,如400或500,或者值的组合,如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或者复杂的类实例,变得更为直观和安全。

相关推荐
S_WEAN32 分钟前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
词却32 分钟前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
星落梦生1 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
汤姆宝库1 小时前
视觉语言模型的实现:LLaVA式投影与指令微调
python·深度学习·语言模型
2601_9679791211 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
FRing0312 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
wefg112 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++
AI创界者13 小时前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc
琳少_15 小时前
java程序设计笔记
java·开发语言·数据库·笔记
2601_9679873716 小时前
python网络工程师自动化运维课程
python·正则表达式·网络工程师·模块·自动化运维