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

如何在Python中永久修改列表?调试为列表元素加'the Great'后缀的代码

问题根因
  • Python中列表是可变对象,但你在make_great函数内直接对参数magicians执行赋值操作时,相当于创建了一个新的局部列表对象,让局部变量magicians指向了这个新地址,完全没有修改外部传入的原始列表的内容。
  • 函数执行完毕后局部变量被销毁,外部的原列表自然没有任何变化。
修复方案

要实现对原列表的永久修改,用切片赋值替换直接赋值即可。切片赋值会直接修改原列表内存地址中存储的内容,不会创建新的列表对象:

# 修复后的make_great函数
def make_great(magicians):
  print("Greatifying Magicians...")
  # 切片赋值修改原列表内容
  magicians[:] = [f"{mag} the Great" for mag in magicians]

# 展示魔术师名单
def show_magicians(magicians):
  for magician in magicians:
    print(magician)

magicians = ["Andrea Haddad", "Shroomy", "Arkos Martinez"]
make_great(magicians)
show_magicians(magicians)
运行结果
Greatifying Magicians...
Andrea Haddad the Great
Shroomy the Great
Arkos Martinez the Great

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:15:07