我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
我想定义一个没有初始化长度的二维数组,如下所示:
Matrix = [][]
但这给出了一个错误:
IndexError:列表索引超出范围
当前回答
这是一个来自C、CPP和Java背景的初学者的代码
rows = int(input())
cols = int(input())
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(0)
matrix.append(row)
print(matrix)
为什么这么长的代码,在Python中也是如此?
很久以前,当我不熟悉Python时,我看到了编写2D矩阵的单行答案,并告诉自己我不会再在Python中使用2D矩阵。(这些单行很吓人,它没有告诉我Python在做什么。还要注意,我不知道这些短手。)
其他回答
为便于阅读而重写:
# 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)
试试看:
rows = int(input('Enter rows\n'))
my_list = []
for i in range(rows):
my_list.append(list(map(int, input().split())))
Use:
matrix = [[0]*5 for i in range(5)]
第一个维度的*5有效,因为在这个级别上数据是不可变的。
要声明一个零(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请参见-->多维数组)
输入矩阵和打印的用户定义功能
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