import numpy as np
前言:
如果您对阅读感到无聊,请跳过前言,因为您已经知道这一点。
我最近在调试时遇到了一个问题。我写了 `A = B = C = np.zeros([3,3]) 我以为我刚刚定义了三个新矩阵。我所做的实际上是不同的。我定义了一个新矩阵(用零填充)和三个标签,每个标签都引用同一个矩阵。让我用下面的例子来说明:
>>> a = b = [0,0]
>>> a
[0,0]
>>> b
[0,0]
>>> # All good so far.
>>> a[0] = 1
>>> a
[1,0]
>>> # Nothing short of what one would expect...
>>> b
[1,0]
>>> # ... but since 'b' is assigned tot he same tuple, it changes as well.
问题:
好。现在我知道这没问题了,对吧?当然我可以写:
A = np.zeros([3,3])
B = np.zeros([3,3])
C = np.zeros([3,3])
一切正常吗?没错,但我同样可以写:
A, B, C = np.zeros([3,3,3])
I would think that the second option uses memory in more efficient way since it defines a 3x3x3 tensor and then 3 labels A, B and C for each of it's layers instead of three separate matrices with possible bits of memory between them.
Which one would you think is better?