我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
要声明一个零(1)矩阵:
numpy.zeros((x, y))
e.g.
>>> numpy.zeros((3, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
或numpy.ones((x,y))例如
>>> np.ones((3, 5))
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
甚至三维都是可能的。(http://www.astro.ufl.edu/~warner/prog/python.html请参见-->多维数组)
其他回答
你应该列出一个列表,最好的方法是使用嵌套的理解:
>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(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]]
在您的[5][5]示例中,您正在创建一个包含整数“5”的列表,并尝试访问其第5项,这自然会引发IndexError,因为没有第5项:
>>> l = [5]
>>> l[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
我正在编写我的第一个Python脚本,我对方阵示例有点困惑,所以我希望下面的示例可以帮助您节省一些时间:
# Creates a 2 x 5 matrix
Matrix = [[0 for y in xrange(5)] for x in xrange(2)]
因此
Matrix[1][4] = 2 # Valid
Matrix[4][1] = 3 # IndexError: list index out of range
如果你只需要一个二维容器来容纳一些元素,你可以方便地使用字典来代替:
Matrix = {}
然后您可以执行以下操作:
Matrix[1,2] = 15
print Matrix[1,2]
这是因为1,2是一个元组,您将其用作索引字典的键。结果类似于哑稀疏矩阵。
如osa和Josap Valls所示,您还可以使用Matrix=collections.defaultdict(lambda:0),以便丢失的元素具有默认值0。
Vatsal进一步指出,这种方法对于大型矩阵可能不是很有效,只应在代码的非性能关键部分使用。
下面是在python中创建矩阵的代码片段:
# get the input rows and cols
rows = int(input("rows : "))
cols = int(input("Cols : "))
# initialize the list
l=[[0]*cols for i in range(rows)]
# fill some random values in it
for i in range(0,rows):
for j in range(0,cols):
l[i][j] = i+j
# print the list
for i in range(0,rows):
print()
for j in range(0,cols):
print(l[i][j],end=" ")
如果我错过了什么,请提出建议。
在Python中,您将创建一个列表列表。您不必提前声明维度,但可以这样做。例如:
matrix = []
matrix.append([])
matrix.append([])
matrix[0].append(2)
matrix[1].append(3)
现在矩阵[0][0]==2,矩阵[1][0]==3。您还可以使用列表理解语法。本示例使用它两次来构建“二维列表”:
from itertools import count, takewhile
matrix = [[i for i in takewhile(lambda j: j < (k+1) * 10, count(k*10))] for k in range(10)]