我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
输入矩阵和打印的用户定义功能
def inmatrix(m,n):
#Start function and pass row and column as parameter
a=[] #create a blank matrix
for i in range(m): #Row input
b=[]#blank list
for j in range(n): # column input
elm=int(input("Enter number in Pocket ["+str(i)+"]["+str(j)+"] ")) #Show Row And column number
b.append(elm) #add value to b list
a.append(b)# Add list to matrix
return a #return Matrix
def Matrix(a): #function for print Matrix
for i in range(len(a)): #row
for j in range(len(a[0])): #column
print(a[i][j],end=" ") #print value with space
print()#print a line After a row print
m=int(input("Enter number of row")) #input row
n=int(input("Enter number of column"))
a=inmatrix(m,n) #call input matrix function
print("Matrix is ... ")
Matrix(a) #print matrix function
其他回答
下面是在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=" ")
如果我错过了什么,请提出建议。
我在逗号分隔的文件中阅读如下:
data=[]
for l in infile:
l = split(',')
data.append(l)
列表“data”是带有索引数据[row][col]的列表列表
公认的答案是正确的,但我花了一段时间才明白,我也可以使用它创建一个完全空的数组。
l = [[] for _ in range(3)]
结果
[[], [], []]
为便于阅读而重写:
# 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)
使用NumPy,可以如下初始化空矩阵:
import numpy as np
mm = np.matrix([])
然后像这样附加数据:
mm = np.append(mm, [[1,2]], axis=1)