Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a flat list to list of lists in python

Tags:

One may want to do the contrary of flattening a list of lists, like here: I was wondering how you can convert a flat list into a list of lists.

In numpy you could do something like:

>>> a=numpy.arange(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:

>>> 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']] 

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

like image 491
oz123 Avatar asked Apr 12 '12 13:04

oz123


People also ask

How do I make a flat list out of a list of lists?

Flattening a list of lists entails converting a 2D list into a 1D list by un-nesting each list item stored in the list of lists - i.e., converting [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9] .

Can you make a list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.

How do I convert a list to a list in Python?

Using map. The map function is used to apply the same function again and again to a sequence of parameters. So we use a lambda function to create a series of list elements by reading each element from the original list and apply map function to it.

How do I convert a list to a nested list in Python?

We can also use the python module names abstract syntax trees or called ast. It has a function named literal_eval which will keep the elements of the given list together and convert it to a new list.


1 Answers

>>> l = ['a', 'b', 'c', 'd', 'e', 'f'] >>> zip(*[iter(l)]*2) [('a', 'b'), ('c', 'd'), ('e', 'f')] 

As it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the zip function each time it returns a tuple. If one of the parameters has less items than the others, items are cut off eg.

>>> l = ['a', 'b', 'c', 'd', 'e', 'f','g'] >>> zip(*[iter(l)]*2) [('a', 'b'), ('c', 'd'), ('e', 'f')] 

If this is the case then it is best to use the solution by @Sven Marnach

How does zip(*[iter(s)]*n) work

like image 89
jamylak Avatar answered Oct 14 '22 23:10

jamylak