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

相关推荐
短剑重铸之日42 分钟前
《SpringBoot4.0初识》第一篇:前瞻与思想
java·开发语言·后端·spring·springboot4.0
2501_941877981 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
lsx2024061 小时前
Python 运算符详解
开发语言
酩酊仙人1 小时前
fastmcp构建mcp server和client
python·ai·mcp
程序炼丹师1 小时前
CMakeLists中 get_filename_component详解
开发语言
꧁Q༒ོγ꧂2 小时前
C++ 入门完全指南(四)--函数与模块化编程
开发语言·c++
且去填词2 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek
listhi5202 小时前
对LeNet-5的matlab实现,识别MINST手写数字集
开发语言·matlab
qq_433554542 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
csbysj20202 小时前
Chart.js 饼图:全面解析与实例教程
开发语言