I need to convert a list into a matrix form .I have written the the code below:
Grid=[]
count=0
for i in range(N):
l=[]
for j in range(N):
l.append(grid[count])
count+=1
Grid.append(l)
here, grid is the input list and when I run it, I get below error.
Traceback (most recent call last):
File "C:/Users/saikr/PycharmProjects/pythonprog/GlowingBacteria.py", line 80, in <module>
ret=gb.findSolution(N,C,D,K,grid)
File "C:/Users/saikr/PycharmProjects/pythonprog/GlowingBacteria.py", line 19, in findSolution
l.append(grid[count])
IndexError: list index out of range
please help me solve this.
You can use another approach for creating matrix using python list.
a = [[x] * m] * n
a
is your desired matrix / multi-dimensional list.
m
stands for the number of column and n
stands for the number of row.
and the list [x]
is the initializer of the list, you can use list comprehension here for initialize these value.
or
N=5
a = []
for i in range(N):
a.append([] * N)
do this for simply create an empty matrix of N x N.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.