首页 > 解决方案 > Python; 原始列表在函数内发生变化

问题描述

在我的函数中,我需要将列表中元素的值更改为默认值(10)而不更改原始列表。

function(orig_list):

dup_list = list(orig_list)

#Setting the appropriate value for the list but don't want to change the original list. 
for i in dup_list:
    if dup_list[dup_list.index(i)][1] == 11 or dup_list[dup_list.index(i)][1] == 12 or dup_list[dup_list.index(i)][1] == 13:
        dup_list[dup_list.index(i)][1] = 10

但是,当我稍后在代码中调用该函数并打印原始列表时,它也发生了变化。我希望函数执行此操作并给我一个值但不更改原始列表。

标签: pythonpython-3.xlistloopsindexing

解决方案


有多种方法可以复制可变数据结构,例如列表和字典。如果只有不可变的成员,浅拷贝就可以工作,但是如果列表中有一个列表,例如,你需要一个深拷贝。

为了显示:

from copy import deepcopy

l = [1,['a', 'b', 'c'],3,4]
l2 = list(l)
l3 = l.copy()
l4 = deepcopy(l)


# Mutate original list
l[0] = 10  # All of the copies are unaffected by this.
l[1][0] = 'f' # All of the copies except for the deep copy are affected by mutating a mutable item inside the shallow copy of the list.

print(l, l2, l3, l4)

# Result:
# [10, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['a', 'b', 'c'], 3, 4]

推荐阅读