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

Python函数中如何通过赋值修改传入列表的引用值?

问题解答

为什么你的代码没生效?

Python里函数参数传递是传对象引用,但你在函数里写nums = [1,2,3,4,5]时,只是把函数内部的局部变量nums重新绑定到了一个新的列表对象上,完全没碰外部test指向的旧列表。所以外部的test自然不会发生变化。

能不能用“赋值”类的方式实现修改?

直接给参数变量赋值新对象不行,但可以通过修改原列表对象的内容来达到类似效果——本质是操作原对象而非重新绑定变量,有两种常用写法:

方法1:切片赋值

直接替换原列表的所有元素:

class Simple:
    def removeDuplicates(self, nums: list[int]) -> int:
        nums[:] = [1, 2, 3, 4, 5]  # 用切片赋值修改原列表内容
        print("in function: ", nums)

simple = Simple()
test = [9, 8, 7, 6]
simple.removeDuplicates(test)
print("after function: ", test)

运行结果:

in function:  [1, 2, 3, 4, 5]
after function:  [1, 2, 3, 4, 5]

方法2:清空原列表再扩展

先清空原列表,再添加新元素:

class Simple:
    def removeDuplicates(self, nums: list[int]) -> int:
        nums.clear()
        nums.extend([1, 2, 3, 4, 5])
        print("in function: ", nums)

simple = Simple()
test = [9, 8, 7, 6]
simple.removeDuplicates(test)
print("after function: ", test)

运行结果和上面一致。

这两种方式都是直接操作原列表对象,所以外部的test会同步看到变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:41:12