Domanda

I have a question about removing the dependency in multidimensional lists in python.

Currently I have a (simplified) code snippet out of my bigger script:

mylist = [ 1,2,3 ]
listreplaced = mylist
listreplaced[0]="test"
print mylist

mylist = [ 1,2,3 ]
listreplaced = list(mylist)
listreplaced[0]="test"
print mylist

#Here it gets tricky
mylist = [ [ 1,2,3 ] ]
listreplaced = list(mylist)
listreplaced[0][0] = "test"
print mylist

mylist = [ [ 1,2,3 ] ]
listreplaced = list(mylist[0])
listreplaced[0] = "test"
print mylist

Which outputs:

[['test', 2, 3]
[1, 2, 3]
[['test', 2, 3]]
[[1, 2, 3]]

As you can see the third example also replaces the first value in the multidimensional list. What I want to do is: no matter how many dimensions the list has, I want a function to make it independent of the lists it was based on. The code would be something like this then:

mylist = [ [ 1,2,3 ] ]
listreplaced = makeIndependentList(mylist)
listreplaced[0][0] = "test"
print mylist

and the result should be [[1, 2, 3]] instead of [['test', 2, 3]]. Does anyone have any ideas about how to write such a function? It should work regardless of the number of dimensions of the list, so if I have a list [ [ [ [ [ [ 1,2,3 ] ] ] ] ] ] it should still become independent on all levels.

Thanks in advance,

Jef

È stato utile?

Soluzione

you just use the copy module ... thats what its there for ...

 from copy import deepcopy

 my_other_list = deepcopy(my_list)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top