Python:numpy __deepcopy__ TypeError [英] Python: Numpy __deepcopy__ TypeError

查看:90
本文介绍了Python:numpy __deepcopy__ TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ndarray上使用deepcopy,并且该行看起来像这样:

I'm trying to use deepcopy on an ndarray, and the line looks like this:

foo = myArray.__deepcopy__()

我得到了:

TypeError: function takes exactly 1 argument (0 given)

我需要一个深层副本,但无法导入副本.

I need a deep copy, and I can't import copy.

推荐答案

copy中的相关代码为:

def deepcopy(x, memo=None, _nil=[]):
    """Deep copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.
    """

    if memo is None:
        memo = {}
        ....
           copier = getattr(x, "__deepcopy__", None)
            if copier:
                y = copier(memo)
...
# If is its own copy, don't memoize.
if y is not x:
    memo[d] = y
    _keep_alive(x, memo) # Make sure x lives at least as long as d
return y

所以memomemoize词典,至少在正确"使用时是这样的

So memo is a memoize dictionary, at least when used 'properly'

因此,如果我将字典作为memo传递,它将改变:

So if I pass a dictionary as memo, it changes that:

In [160]: dd={}
In [161]: A2=copy.deepcopy(A,memo=dd)
In [162]: dd
Out[162]: 
{2814755008: array([[[0, 1, 0, 0, 0, 0],
         [0, 0, 1, 0, 0, 1],
         [0, 0, 0, 1, 0, 1],
         [1, 0, 0, 0, 1, 0]],

        [[0, 0, 1, 0, 0, 0],
         [0, 0, 1, 1, 0, 0],
         [0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0]]]), 2814808588: [array([[[0, 1, 0, 0, 0, 0],
          [0, 0, 1, 0, 0, 1],
          [0, 0, 0, 1, 0, 1],
          [1, 0, 0, 0, 1, 0]],

         [[0, 0, 1, 0, 0, 0],
          [0, 0, 1, 1, 0, 0],
          [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0]]])]}
In [163]: id(A)
Out[163]: 2814755008
In [167]: id(dd[id(A)])
Out[167]: 2814568472
In [168]: id(A2)
Out[168]: 2814568472

memo保留副本的记录.我不知道第二项是什么.

The memo keeps a record of the copy. I don't know what the 2nd item is.

如果我要求使用相同的备忘进一步复制,它会提供已备忘的数组,而不是新的副本.

And if I ask for another deep copy with the same memo, it gives the memoized array rather than a new copy.

In [173]: A3=copy.deepcopy(A,memo=dd)
In [174]: id(A2)
Out[174]: 2814568472
In [175]: id(A3)
Out[175]: 2814568472

如果数组是对象dtype,则deepcopy可能会有所不同.备忘录肯定看起来不一样.

If an array is object dtype, the deepcopy might make a difference. The memo certainly looks different.

这篇关于Python:numpy __deepcopy__ TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆