[英]Python list in list undo
I'm making a program that will do some operations like add, insert, pop on a list of numbers. 我正在制作一个程序,该程序将执行一些操作,例如加,插入,弹出数字列表。 I have to also make an "undo" function and for that I thought about making a list in list to save up my list every step of the way but my tests are not working.
我还必须做一个“撤消”功能,为此,我考虑在列表中创建一个列表以保存列表的每一步,但是我的测试无法正常工作。 Here's the code:
这是代码:
def backup(l):
lbackup.append(list(l))
<-- here I save the list every step of the way by calling this function <-在这里,我通过调用此函数来保存列表的每一步
> def undo(l):
> l=lbackup[len(lbackup)-1] # here I give my list the previous list
> del lbackup[len(lbackup)-1] # here I delete the sublist from the history
My test: 我的测试:
def testUndo():
add(lista, 1)
backup(lista)
add(lista, 2)
backup(lista)
add(lista,111111)
print(lbackup)
print(lista)
undo(lista)
print(lista)
print(lbackup)
So I checked the inside of the Undo function and it's working! 因此,我检查了“撤消”功能的内部,它正在起作用! It actually changed the value of my list to what I wanted but once it left the function and got to the print after undo in the test... it had the same values again.
它实际上将列表的值更改为我想要的值,但是一旦它离开该函数并在测试中撤消后立即打印出来,它又具有相同的值。 I know lists are mutable and that might be a problem but is there anything I could do?
我知道列表是可变的,这可能是个问题,但是我能做些什么吗? Sorry if I wasnt clean enough.
对不起,如果我不够干净。
When you call, say, undo(lista)
, the l
inside of undo
may be the same list as lista
, but assigning to l
does not change lista
. 当您调用
undo(lista)
, undo
内部的l
可能与lista
相同,但分配给l
不会改变lista
。 If instead you had undo
return l
, and assign the value returned by undo
back to list
, that would make the change you seem to want. 相反,如果你不得不
undo
回报l
,并指定返回的值undo
回到list
,这将使你似乎想改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.