Thursday, April 12, 2012

convert a flat list to list of list in python

Normally, you want to go the other way around, like here. I was wondering how you can convert a flat list to a list of list, quasy reshaping array in python



In numpy you could do something like:



>>> a=numpy.aranage(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])


I was wondering how you do the opposite, and my usual solution is something like:



>>> list
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(diffe2),2):
... newList.append(diffe2[i], diffe2[i+1])
>>> newList
[['a', 'b'], ['c', 'd'], ['e', 'f']]


is there a more "Pythonic" way to do it?





No comments:

Post a Comment