我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
注意这个简短的表达,请参见@F.J的答案中的完整解释
其他回答
下面是在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调用此“列表理解”。
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]
#您现在可以向列表中添加项目:
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
注意,矩阵是“y”地址主,换句话说,“y索引”在“x索引”之前。
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
尽管您可以根据自己的意愿命名它们,但我这样看是为了避免索引中可能出现的一些混淆,如果您对内部和外部列表都使用“x”,并且希望使用非方形矩阵。
这就是词典的用途!
matrix = {}
可以通过两种方式定义键和值:
matrix[0,0] = value
or
matrix = { (0,0) : value }
结果:
[ value, value, value, value, value],
[ value, value, value, value, value],
...
通常,go to模块是NumPy:
import numpy as np
# Generate a random matrix of floats
np.random.rand(cols,rows)
# Generate a random matrix of integers
np.random.randint(1, 10, size=(cols,rows))
如果要创建空矩阵,正确的语法是
matrix = [[]]
如果你想生成一个大小为5、填充有0的矩阵,
matrix = [[0 for i in xrange(5)] for i in xrange(5)]