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

相关推荐
华研前沿标杆游学1 小时前
【标杆研学】走进茅台集团|对标学习长期主义与匠心精神
python
阿里嘎多学长1 小时前
2026-10-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管
GitFun2 小时前
KDJ vs RSI:11年数据实测,金叉死叉输了48个点
python·股票·量化交易
李可以量化2 小时前
从零读懂配对交易(上):从套利本源到配对交易的核心逻辑
python·区块链·量化交易·通达信·qmt
CCblandy2 小时前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构
wangchunyu1142 小时前
Python 数据可视化实战入门教程
开发语言·python·信息可视化
蜗牛互联网2 小时前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python
SL_staff3 小时前
当规则引擎开始‘懂业务’:JVS-Rules金融风控四大原生能力拆解
java·python·全栈
蚰蜒螟3 小时前
从内核启动到 Java NIO:一次 socket accept 的源码串联之旅
java·python·nio
学逆向的4 小时前
C 突破编译器限制
c语言·开发语言·网络安全