一种解决方案是使用一个numpy的(download here)matrix
:
>>> from numpy import zeros, matrix
>>> n = 2
>>> mat = matrix(zeros([3*n, 7]))
>>> mat
matrix([[ 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., 0., 0., 0., 0., 0., 0.]])
然而,如上所注意到@joris,具有numpy的矩阵中的所有数据必须是相同的类型。
>>> mat[0,2] = 14
>>> mat
matrix([[ 0., 0., 14., 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., 0., 0., 0.]])
>>> mat[0,1] = 's'
Traceback (most recent call last):
File "<pyshell#139>", line 1, in <module>
mat[0,1] = 's'
ValueError: could not convert string to float: s
你可能想使用嵌套list
代替,因为这是迄今为止一个更灵活,通用的数据类型,除了更容易找到窍门。因为@Mike Graham在解释他们时做了正确的工作,所以我会告诉你this question。你可能想要定义一个方法,如:
def shape_zeros(n):
# Here's where you build up your "matrix"-style nested list
pass # The pass statement does nothing!
这里有几个提示填补了上述函数的代码体。首先,你可以构建重复的整个列表与*
星号运营商:
>>> row = [0] * 7
>>> row
[0, 0, 0, 0, 0, 0, 0]
接下来,可以将列表中嵌套列表;
>>> mat = []
>>> n = 2
>>> for i in range(n*3):
mat.append(row)
>>> mat
[[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, 0, 0, 0, 0, 0, 0]]
>>> mat[0][0] = 1
>>> mat
[[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0]]
您可以单独创建子列表(行)或使用list(old_list)
构造函数做出避免上述问题:但走动列表时,随着列表的名称实际上是一样的指针要小心复制。当你建立它的权利,你可以像这样访问/操纵一个嵌套列表元素:
>>> mat[0][0] = 1
>>> mat[1][2] = 'Q_Q'
>>> mat[2][0] = 3
>>> mat[2][2] = 5
>>> mat
[[1, 0, 0, 0, 0, 0, 0],
[0, 0, 'Q_Q', 0, 0, 0, 0],
[3, 0, 5, 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]]
祝你好运!
请编辑您的问题以重新格式化您的代码。 –
为什么不把矩阵放在首位呢? 'mat = numpy.zeros((3,7))'。 – katrielalex
矩阵的用途是什么?因为如果你想使用numpy数组,你不能像这样混合数字和字符串。 – joris