有时人们希望做的不是将列表扁平化,而是将一个扁平的列表转换为一个嵌套列表,就像这里所描述的:https://dev59.com/qnNA5IYBdhLWcg3wdtld。我想知道如何在Python中将一个扁平的列表转换为一个嵌套列表。
在NumPy中,您可以尝试:
>>> a=numpy.arange(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
我想知道如何做相反的操作,我的通常解决方案类似于:
>>> Mylist
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(Mylist),2):
... newList.append(Mylist[i], Mylist[i+1])
>>> newList
[['a', 'b'], ['c', 'd'], ['e', 'f']]
有没有更符合Python风格的方法来完成这个任务?
list
作为变量名,因为有内置函数list()
。 - jamylak