使用zeros创建numpy数组

1 投票
2 回答
3034 浏览
提问于 2025-04-18 08:44

我一直在尝试用Python的numpy模块创建一个6乘6的数组,所有元素都设置为0.0:

import numpy as np
RawScores = np.zeros((6,6), dtype=np.float)
print RawScores

这个输出结果是:

[[ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]]

为什么没有逗号?没有逗号的话,这还是数组吗?

2 个回答

0

如果你特别在意数组中的逗号,你可以重新定义numpy打印数组的方式,这里有个非常简单的例子:

import numpy as np
RawScores = np.zeros((6,6), dtype=np.float)
def add_comma(num):
  return "%g, " % num

np.set_printoptions(formatter={"all":add_comma})
print RawScores
[[0,  0,  0,  0,  0,  0, ]    
 [0,  0,  0,  0,  0,  0, ]
 [0,  0,  0,  0,  0,  0, ]
 [0,  0,  0,  0,  0,  0, ]
 [0,  0,  0,  0,  0,  0, ]
 [0,  0,  0,  0,  0,  0, ]]
3

这是因为 print 函数会调用 __str__ 方法,而不是 __repr__ 方法。下面有个例子。想了解这两个方法之间的详细区别,可以点击这里

# Python 2D List
>>> [[0]*6]*6
[[0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0]]

>>> import numpy as np
>>> np.zeros((6,6))
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

# calls __repr__
>>> a = np.zeros((6,6))
>>> a
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

# calls __str__
>>> print a
[[ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.]]

撰写回答