You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何正确编写返回多元组的多行return语句?

Python多行return多元素元组时丢失返回值的解决方法

我有一个Python函数,返回由多个元组组成的元组,原函数写法如下:

def test_real():
    return (item_a_long_name, item_b_long_name), (item_c_long_name, item_d_long_name), ..., (item_x_long_name, item_y_long_name)

在Jupyter Notebook中,这个return语句会显示为单行,元素名称太长时难以完整查看。我尝试拆分写成多行,但结果不符合预期:

def test():
    return (1,2), (3,4)

print("test:", test())

def test2():
    return (
        1,2
    ), 
    (
        3,4
    )

print("test2:", test2())

输出结果:

test: ((1, 2), (3, 4))
test2: ((1, 2),)

test2只返回了第一个元组,请问如何正确编写多行的return语句,同时返回所有元组?


解决方法

方法1:用外层括号包裹所有返回元素

将所有要返回的元组放在一个大括号内,让Python识别为一个完整的元组返回:

def test2():
    return (
        (1, 2),
        (3, 4)
    )

print("test2:", test2())  # 输出:test2: ((1, 2), (3, 4))

方法2:在行尾添加反斜杠连接多行

在第一个元组的逗号后添加反斜杠,明确告诉Python该行未结束:

def test2():
    return (
        1,2
    ), \
    (
        3,4
    )

print("test2:", test2())  # 输出:test2: ((1, 2), (3, 4))

方法3:利用括号隐式换行简化排版

如果返回内容本身就在括号结构中,Python支持隐式换行,也可以这样排版:

def test_real():
    return (item_a_long_name, item_b_long_name), \
           (item_c_long_name, item_d_long_name), \
           (item_x_long_name, item_y_long_name)

原因说明

原来的写法出错是因为:Python遇到换行时,若前一行的逗号后没有反斜杠,也没有被外层括号包裹,会自动将逗号后的换行视为语句结束。return (1,2), 会被解析为返回一个仅包含(1,2)的单元素元组(末尾的逗号正是单元素元组的定义标识),后面的(3,4)会被当作独立语句,不会被return返回。

内容的提问来源于stack exchange,提问作者stackbiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:33:24