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

相关推荐
环能jvav大师2 分钟前
基于R语言的统计分析基础:使用SQL语句操作数据集
开发语言·数据库·sql·数据分析·r语言·sqlite
吱吱鼠叔5 分钟前
MATLAB方程求解:1.线性方程组
开发语言·matlab·php
今天也要加油丫7 分钟前
`re.compile(r“(<.*?>)“)` 如何有效地从给定字符串中提取出所有符合 `<...>` 格式的引用
python
Antonio91510 分钟前
【CMake】使用CMake在Visual Studio内构建多文件夹工程
开发语言·c++·visual studio
LyaJpunov24 分钟前
C++中move和forword的区别
开发语言·c++
程序猿练习生28 分钟前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
一名路过的小码农38 分钟前
C/C++动态库函数导出 windows
c语言·开发语言·c++
m0_6312704041 分钟前
标准c语言(一)
c语言·开发语言·算法
万河归海42841 分钟前
C语言——二分法搜索数组中特定元素并返回下标
c语言·开发语言·数据结构·经验分享·笔记·算法·visualstudio
Messiah___1 小时前
【论文阅读】Slim Fly: A Cost Effective Low-Diameter Network Topology 一种经济高效的小直径网络拓扑
开发语言·php