在Python中将一维列表转换为具有给定行长的二维列表 [英] Converting a 1D list into a 2D list with a given row length in python
本文介绍了在Python中将一维列表转换为具有给定行长的二维列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法可以将一维列表转换为具有给定行长的二维列表?
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]
我要将上面的列表转换成3 x 3的表格,如下所示:
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]]
我知道我可以通过创建一个名为 myList2
的新2D列表并使用2个嵌套的for循环将该元素插入 MyList2
中来完成此操作.就像 MyList2 [x] [y] = myList [i] i ++
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)
谢谢!
推荐答案
使用列表理解带有切片:
>>> 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]]
这篇关于在Python中将一维列表转换为具有给定行长的二维列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文