Converting a 1D list into a 2D list with a given row length in python [duplicate]

有些话、适合烂在心里 提交于 2021-02-10 04:27:12

问题


Is there an easy way to convert a 1D list into a 2D list with a given row length?

Suppose I have a list like this:

myList =  [1, 2, 3, 4, 5, 6, 7, 8, 9]

I want to convert the above list into a 3 x 3 table like below:

myList = [[1,2,3],[4,5,6],[7,8,9]]

I know I can accomplish this by creating a new 2D list called myList2 and inserting the element into MyList2 using 2 nested for loops. Like MyList2[x][y] = myList[i] i++

I think there should be a better way to do it (without using external libraries or modules)

Thanks!


回答1:


Using list comprehension with slice:

>>> myList =  [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> n = 3
>>> [myList[i:i+n] for i in range(0, len(myList), n)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


来源:https://stackoverflow.com/questions/27371064/converting-a-1d-list-into-a-2d-list-with-a-given-row-length-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!