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?
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] .
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.
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.
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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With