我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
如果在开始之前没有大小信息,请创建两个一维列表。
list 1: To store rows
list 2: Actual two-dimensional matrix
将整行存储在第一个列表中。完成后,将列表1追加到列表2中:
from random import randint
coordinates=[]
temp=[]
points=int(raw_input("Enter No Of Coordinates >"))
for i in range(0,points):
randomx=randint(0,1000)
randomy=randint(0,1000)
temp=[]
temp.append(randomx)
temp.append(randomy)
coordinates.append(temp)
print coordinates
输出:
Enter No Of Coordinates >4
[[522, 96], [378, 276], [349, 741], [238, 439]]
其他回答
l=[[0]*(L) for _ in range(W)]
将快于:
l = [[0 for x in range(L)] for y in range(W)]
如果你真的想要一个矩阵,你最好使用numpy。numpy中的矩阵运算通常使用二维数组类型。创建新阵列有多种方法;其中最有用的是zeros函数,它接受一个形状参数并返回一个给定形状的数组,值初始化为零:
>>> import numpy
>>> numpy.zeros((5, 5))
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.]])
以下是创建二维数组和矩阵的一些其他方法(为了紧凑,去掉了输出):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy也提供了一种矩阵类型,但它不再推荐用于任何用途,将来可能会从numpy中删除。
Use:
matrix = [[0]*5 for i in range(5)]
第一个维度的*5有效,因为在这个级别上数据是不可变的。
我在逗号分隔的文件中阅读如下:
data=[]
for l in infile:
l = split(',')
data.append(l)
列表“data”是带有索引数据[row][col]的列表列表
这就是词典的用途!
matrix = {}
可以通过两种方式定义键和值:
matrix[0,0] = value
or
matrix = { (0,0) : value }
结果:
[ value, value, value, value, value],
[ value, value, value, value, value],
...