在 Python 中复制字符串列表的最佳方法是什么?
我是Python新手,为了将一个矩阵复制到另一个矩阵,我正在做:
import copy
matrix1.append(copy.deepcopy(matrix2))
有更好的,也许更短的方法吗?
--update:
类型是字符串列表,例如 [["asdf", "fdsa"], ["zxcv", "vcxz"]]
,而我想要将其添加到我的其他列表中,但我不希望它们是相同的引用(我想编辑一个而不更改另一个)。
I'm new to Python, and to copy a matrix to another, I'm doing:
import copy
matrix1.append(copy.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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确定需要复制任何内容吗?大多数情况下,最好不要像这样复制数据。这样做意味着您将改变副本。很多时候,只需要制作一个新的东西而不是改变一个副本,这最终会随着程序的开发而减少出错的可能性。您打算对副本做什么?您确定在创建新事物时而不是在创建新事物之后这样做不是更好吗?
如果我要复制
x = [["asdf", "fdsa"], ["zxcv", "vcxz"]]
,我会写 < code>copy = [list(ss) for ss in x](或map(list, x)
)。这使得我在做什么非常清楚。当我确实需要复制数据时,我会避免使用
复制
模块。由于其工作方式,复制模块可能会失败或给出错误的答案。当您不知道要复制的内容的结构或内容时,它通常很有用,但如果您不知道,您通常会遇到比“如何复制它?”更根本的问题,即“我如何使用它?”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?"如果你的矩阵实际上是一个列表,那么这更简单:
你的代码正在扩展
matrix1
,它必须事先存在,为什么除了添加新内容之外还要保留其原始内容?更新:
是的,你所拥有的是最好的方法。
If your matrix is actually a list, then this is simpler:
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.
另一种方式:
它是否有超过 2 维的维度? 请继续使用 DeepCopy :
否则,如果您想附加,
Another way:
Does it have more than 2 dimensions? Otherwise stay with deepcopy
if you want to append: