Python:创建数组的副本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2452321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:40:50  来源:igfitidea点击:

Python: Create a duplicate of an array

pythonlistpointersarrays

提问by Dan

I have an double array

我有一个双数组

alist[1][1]=-1
alist2=[]
for x in xrange(10):
    alist2.append(alist[x])
alist2[1][1]=15

print alist[1][1]

and I get 15. Clearly I'm passing a pointer rather than an actual variable... Is there an easy way to make a seperatedouble array (no shared pointers) without having to do a double for loop?

我得到 15. 显然我传递的是一个指针而不是一个实际的变量......有没有一种简单的方法来制作一个单独的双数组(没有共享指针)而不必做一个双循环

Thanks, Dan

谢谢,丹

采纳答案by Mike Graham

A list of lists is not usually a great solution for making a 2d array. You probably want to use numpy, which provides a very useful, efficient n-dimensional array type. numpy arrays can be copied.

列表列表通常不是制作二维数组的好方法。您可能想要使用 numpy,它提供了一种非常有用、高效的 n 维数组类型。可以复制 numpy 数组。

Other solutions that are usually better than a plain list of lists include a dict with tuples as keys (d[1, 1]would be the 1, 1 component) or defining your own 2d array class. Of course, dicts can be copied and you could abstract copying away for your class.

通常比普通列表更好的其他解决方案包括以元组为键的字典(d[1, 1]将是 1, 1 组件)或定义您自己的二维数组类。当然,dicts 可以被复制,你可以为你的班级抽象复制。

To copy a list of lists, you can use copy.deepcopy, which will go one level deep when copying.

要复制列表列表,您可以使用copy.deepcopy,它会在复制时深入一层。

回答by msw

I think copy.deepcopy()is for just this case.

我认为copy.deepcopy()仅适用于这种情况。

回答by sth

You can use somelist[:], that is a slice like somelist[1:2]from beginning to end, to create a (shallow) copy of a list. Applying this to your for-loop gives:

您可以使用somelist[:],即somelist[1:2]从头到尾的切片,创建列表的(浅)副本。将此应用于您的 for 循环会给出:

alist2 = []
for x in xrange(10):
   alist2.append(alist[x][:])

This can also be written as a list comprehension:

这也可以写成列表推导式:

alist2 = [item[:] for item in alist]

回答by Dyno Fu

make a copy of the list when append.

追加时制作列表的副本。

  alist2.append(alist[x][:])

回答by EMP

If you're already looping over the list anyway then just copying the inner lists as you go is easiest, as per seanmonstar's answer.

如果您已经在遍历列表,那么根据seanmonstar的回答,随手复制内部列表是最简单的。

If you just want to do a deep copy of the list you could call copy.deepcopy()on it.

如果你只想做一份列表的深层副本,你可以调用copy.deepcopy()它。

回答by seanmonstar

Usually you can do something like:

通常,您可以执行以下操作:

new_list = old_list[:]

So you could perhaps throw that in your singular for loop?

所以你也许可以把它放在你的单一 for 循环中?

for x in range(10):
    alist2.append(alist[x][:])