【问题标题】:python; original list changing within functionPython;原始列表在函数内发生变化
【发布时间】: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


【解决方案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]

【讨论】:

  • 不幸的是,我不允许使用导入来完成此代码。有没有办法在不导入的情况下进行深层复制?
  • 你可以做一个浅拷贝,然后递归地挖掘数据结构并用任何定义了拷贝方法的结构的浅拷贝进行替换。
【解决方案2】:

如果不允许您导入任何内容来深度复制列表,那么您可以使用简单的递归函数自己完成。我下面的示例假设您的列表仅包含不可变项(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 值的新列表中。)

然后,一旦您有了原始列表的深层副本的新列表,您就可以像以前的解决方案一样修改原始列表

【讨论】:

  • 为什么不让你的变量名喘口气呢? deep_copy_list 不是比deepcopylist 清晰得多吗?
  • 当然 deep_copy_list 也不错,它一开始是 deepcopy 似乎找到了,但后来我决定添加一个“列表”限定符,它有点长。我会扔在_s
猜你喜欢
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2022-01-07
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 2019-05-09
相关资源
最近更新 更多