【发布时间】:2020-02-27 00:08:27
【问题描述】:
在我的函数中,我需要在不更改原始列表的情况下将列表中元素的值更改为默认值(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
但是,当我稍后在代码中调用该函数并打印原始列表时,它也发生了变化。我希望函数执行此操作并给我一个值但不更改原始列表。
【问题讨论】:
-
是的,因为
list(orig_list)做了一个浅拷贝。你需要一个深拷贝。请注意,从不循环执行dup_list[dup_list.index(i)]。这是不必要的二次时间,如果列表中有重复项,则实际上是不正确的。相反,迭代项目 和 索引,for index, item in enumerate(dupe_list): ... -
你可以使用
dup_list = orig_list[:] -
这能回答你的问题吗? How to clone or copy a list?
-
@bbrodrigues no,
.copy()创建一个浅拷贝。 任何列表副本都可以按照您显示的方式工作。
标签: python python-3.x list loops indexing