在我的函数中,我需要将列表中元素的值更改为默认值(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
但是,当我稍后在代码中调用该函数并打印原始列表时,它也发生了变化。我希望函数执行此操作并给我一个值,但不要更改原始列表。
答案 0 :(得分:1)
复制可变数据结构(例如列表和字典)的方式有很多。如果只有不可变的成员,则浅表副本会起作用,但是,例如,如果列表中有列表,则需要深层副本。
说明:
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]
答案 1 :(得分:0)
如果不允许您导入任何内容以深层复制列表,则可以使用简单的递归函数自己进行操作。下面的示例假定您的列表仅包含不可变项(float,int,str,tuple等)及其相同列表。例如,它不会深度复制字典(但您可以添加字典):
old = [[1, 2,3], [3, 4,[2, 3, 4], 2, [1,2]]]
def deep_copy_list(inlist):
results = []
for item in inlist:
if type(item) != list: # item is not a list so just append to results
results.append(item)
else:
results.append(deep_copy_list(item)) # item is a list so append a copy
return results
new = deep_copy_list(old)
print("id of element 0 of old is", id(old[0]))
print("id of element 0 of new is", id(new[0]))
id of element 0 of old is 136833800
id of element 0 of new is 151480776
(打印语句仅显示(例如)旧列表元素0中的列表已复制到具有新id值的新列表中。)
然后,有了新列表(该列表是原始列表的深层副本),就可以像以前的解决方案一样修改原始列表