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

Python函数返回值使用问题:为何无法添加到列表且返回None?

问题分析与解决

你的代码里r的值根本没丢,打印出3已经证明了这一点。问题出在列表的append()方法上:

核心原因

Python中列表的append()方法是原地修改原列表,它的返回值是None。你写的r2 = r2.append(r)相当于把append()返回的None赋值给了r2,覆盖了原来的列表,所以最后打印r2会得到None。

正确写法

只需要直接调用append(),不用赋值回r2:

r2 = ["1","2"]

def FunctionA():
    data = "3"
    return data

r = FunctionA()
print(r)

# 直接调用append,原地修改r2,不用赋值
r2.append(r)

print(r2)  # 输出: ['1', '2', '3']

关于值的传递

如果需要把返回值传递给其他函数,直接用r这个变量就行,比如:

def another_func(value):
    print(f"收到的值:{value}")

another_func(r)  # 输出: 收到的值:3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:02:02