我想定义一个没有初始化长度的二维数组,如下所示:

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]]

其他回答

为便于阅读而重写:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

可以通过将两个或多个方括号或第三个方括号([],用逗号分隔)与方括号嵌套来创建一个空的二维列表,如下所示:

Matrix = [[], []]

现在假设您想将1附加到矩阵[0][0],然后键入:

Matrix[0].append(1)

现在,键入矩阵并按Enter键。输出将为:

[[1], []]

如果您输入以下语句

Matrix[1].append(1)

那么矩阵将是

[[], [1]]

通常,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))

我在逗号分隔的文件中阅读如下:

data=[]
for l in infile:
    l = split(',')
    data.append(l)

列表“data”是带有索引数据[row][col]的列表列表

下面是在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=" ")

如果我错过了什么,请提出建议。