What is the best way to copy a list of lists of strings in Python?
I'm new to Python, and to copy a matrix to another, I'm doing:
import copy
matrix1.append(copy开发者_如何学Go.deepcopy(matrix2))
Is there a better, maybe a shorter, way?
--update:
The types are lists of strings, like [["asdf", "fdsa"], ["zxcv", "vcxz"]]
, and I want to add this to my other list, but I don't want them to be the same reference (I want to edit one without change the other).
Are you sure you need to copy anything? The strong majority of the time, it's best not to copy data like this. Doing so implies you're going to mutate the copy. Very often it's possible just to make a new thing rather than to mutate a copy, which ends up being less errorprone as your program develops. What were you planning to do with the copy, and are you sure it isn't better done while creating the new thing rather than after?
If I were to copy
x = [["asdf", "fdsa"], ["zxcv", "vcxz"]]
, I would writecopy = [list(ss) for ss in x]
(ormap(list, x)
). This makes it pretty clear exactly what I'm doing.I avoid the
copy
module when I do need to copy data. Because of the way it works, the copy module can fail or give wrong answers. It mostly promises to be useful when you don't know the structure or content of the stuff you're copying, but if you don't know that, you usually have a more fundamental problem than "how do I copy it?", namely, "how do I use it?"
If your matrix is actually a list, then this is simpler:
import copy
matrix1 = copy.deepcopy(matrix2)
Your code is extending matrix1
, which would have to exist beforehand, and why are you preserving its original contents in addition to adding the new stuff?
UPDATE:
Yes, what you have is the best way.
Another way:
original = [[1,2],[3,4]]
copy = [i[:] for i in original]
Does it have more than 2 dimensions? Otherwise stay with deepcopy
if you want to append:
matrix1.append([i[:] for i in original])
精彩评论