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

相关推荐
wt_cs2 分钟前
身份证实名认证接口数字时代的信任基石-node.js实名认证集成
开发语言·node.js·php
爱编程的鱼20 分钟前
C# 结构(Struct)
开发语言·人工智能·算法·c#
Tiger_shl21 分钟前
【Python语言基础】24、并发编程
java·数据库·python
<<26 分钟前
基于Django的权限管理平台
后端·python·django
只可远观31 分钟前
Flutter Dart 循环语句 for while do..while break、continue
开发语言·javascript·ecmascript
QMT量化交易1 小时前
如何解决PyQt从主窗口打开新窗口时出现闪退的问题
python·pyqt
databook1 小时前
『Plotly实战指南』--样式定制高级篇
python·数据分析·数据可视化
吴_知遇1 小时前
【华为OD机试真题】428、连续字母长度 | 机试真题+思路参考+代码解析(E卷)(C++)
开发语言·c++·华为od
basketball6162 小时前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
兔子蟹子2 小时前
Java集合框架解析
java·windows·python