我有几个列表,我希望能够在整个代码中编辑列表中的项目,然后在以后将它们全部重置为初始值。在
下面是一个例子:
list_a = [0, 1, 2]
list_b = [list_a, 3, 4]
list_c = [6, 7]
list_d = [8, 9]
lists = [0, list_b, 5, list_c, list_d]
#As you can see, lists are of varying length, and sometimes nested multiple times.
print(lists)
Out>>> [0, [[0, 1, 2], 3, 4], 5, [6, 7], [8, 9]]
#Currently, I'm saving the important items of "lists" in the first item, like this:
lists[0] = lists[1:]
#Then I edit the values of various items, like this:
lists[1][0][2] = 0
lists[2] = 0
lists[3][1] = 0
lists[4][1] = 0
print(lists[1:])
Out>>> [[[0, 1, 0], 3, 4], 0, [6, 0], [8, 0]]
#Then I try to reset those values to the originals that I stored in lists[0]
lists[1:] = lists[0]
print(lists[1:])
Out>>> [[[0, 1, 0], 3, 4], 5, [6, 0], [8, 0]]
如您所见,此方法适用于list[2],因为该项是一个值,而不是嵌套列表。似乎即使我使用[1:]在列表[0]中进行复制,对嵌套列表的引用是被复制的内容,而不是那些嵌套列表中的值。在
如何正确地将列表[1]的值复制到列表[0]中,然后再复制回来,而不让两个副本引用同一个索引?在
或者也许有一种更简单的方法来实现同样的预期结果,将列表中的所有项都返回到它们的原始值?在
使用深度复制:https://docs.python.org/3/library/copy.html
这将复制对象以及子对象。在
使用persistent data structures。避免变异可以实现更大程度的共享,并避免像这样的距离的恐怖行为。在
例如:
另外,Python有非列表变量。随机值列表的第一个元素是一个奇怪的“保存”东西的地方。考虑到上述情况,您可以将原始值保留在另一个变量中。例如:
^{pr2}$现在,您可以使用
lists
来绕来绕去,当您厌倦了它,lists = original
会让您回到初始状态。在相关问题 更多 >
编程相关推荐