简体   繁体   English

如何从单个列表中创建列表列表?

[英]how to create a list of lists out of a single list?

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.在这里, grid 是输入列表,当我运行它时,出现以下错误。

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.您可以使用另一种方法使用 python 列表创建矩阵。

  a = [[x] * m] * n

a is your desired matrix / multi-dimensional list. a是您想要的矩阵/多维列表。

m stands for the number of column and n stands for the number of row. m代表列数, n代表行数。

and the list [x] is the initializer of the list, you can use list comprehension here for initialize these value.并且列表[x]是列表的初始化器,您可以在这里使用列表理解来初始化这些值。

or或者

  N=5
  a = []
  for i in range(N):
      a.append([] * N)

do this for simply create an empty matrix of N x N.这样做只是为了创建一个 N x N 的空矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM