Python循环中返回列表元素值与打印值不一致问题求助
问题分析与解决方案
嘿,这个问题其实是Python里可变对象引用的经典“坑”,我来帮你搞明白为啥会这样,以及怎么解决~
问题根源
在Python中,列表是可变对象,当你执行after_move_list = game_list[move_counter - 1]这行代码时,并没有创建一个新的列表,只是把after_move_list指向了game_list里对应元素的内存引用。也就是说,你后续修改after_move_list的所有操作,其实都是在修改同一个底层列表对象。
所以每次循环里,你把after_move_list添加到game_list时,只是把同一个引用重复加了进去。最后当循环结束,所有引用指向的都是最后一次修改后的列表,自然返回的game_list全是[['5', 'b', 'c'], ['d', 'e', 'f']]了。
解决方法
要解决这个问题,你需要每次创建原列表的独立副本,而不是直接引用原列表。因为你的列表是嵌套结构(列表里套列表),所以需要用到深拷贝(或者手动嵌套复制):
方法1:使用copy.deepcopy()(最省心的方式)
copy.deepcopy()会递归复制所有嵌套的可变对象,生成一个完全独立的新列表:
import copy def list_maker(): game_list = [] game_list += [[['a', 'b', 'c'],['d', 'e', 'f']]] move_counter = 1 while move_counter <= 5: # 创建原列表的深拷贝,生成独立的新对象 after_move_list = copy.deepcopy(game_list[move_counter - 1]) after_move_list[0][0] = str(move_counter) print(after_move_list, '\n') game_list += [after_move_list] move_counter += 1 return game_list
方法2:手动嵌套复制(不需要额外模块)
如果不想导入copy模块,可以手动遍历嵌套层,复制每个子列表:
def list_maker(): game_list = [] game_list += [[['a', 'b', 'c'],['d', 'e', 'f']]] move_counter = 1 while move_counter <= 5: original = game_list[move_counter - 1] # 复制外层列表,同时复制每个子列表 after_move_list = [row.copy() for row in original] after_move_list[0][0] = str(move_counter) print(after_move_list, '\n') game_list += [after_move_list] move_counter += 1 return game_list
验证结果
现在运行修改后的代码,返回的game_list就会和你打印的内容完全一致了:
result = list_maker() print(result) # 输出: # [[['a', 'b', 'c'], ['d', 'e', 'f']], [['1', 'b', 'c'], ['d', 'e', 'f']], [['2', 'b', 'c'], ['d', 'e', 'f']], [['3', 'b', 'c'], ['d', 'e', 'f']], [['4', 'b', 'c'], ['d', 'e', 'f']], [['5', 'b', 'c'], ['d', 'e', 'f']]]
内容的提问来源于stack exchange,提问作者iWenn
相关产品推荐
相关产品推荐

