Most pythonic (and efficient) way to nest a list

my list:

mylist=[1,2,3,4,5,6]

I would like to convert mylist to a list of pairs:

[[1,2],[3,4],[5,6]]

Is there a pythonic way? Understanding the list? Itertools?

+5
source share
5 answers

[mylist[2*n:2*n+2] for n in xrange(len(mylist)/2)]

This solution combines the use of lists and slicing to extract pairs in the source list and create a list of slices.

Alternatively [mylist[n:n+2] for n in xrange(0, len(mylist), 2)], which is the same, with the exception xrange, it is calculated in two, not in slices. Thanks to Steven Rumbalski for the offer.

And now for something completely different: here is a solution (ab) that uses an zipephemeral function instead of an intermediate destination:

>>> (lambda i: zip(i, i))(iter(mylist))
[(1, 2), (3, 4), (5, 6)]
+2
source

Yeppers, - :

>>> groupsize = 2
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2],[3,4],[5,6]]
>>> groupsize = 3
>>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)]
[[1,2,3],[4,5,6]]

range , python 2 (, ,), range xrange, .

+9

My preferred technique:

>>> mylist = [1, 2, 3, 4, 5, 6]
>>> mylist = iter(mylist)
>>> zip(mylist, mylist)
[(1, 2), (3, 4), (5, 6)]

I usually use generators instead of lists, so line 2 is usually not required.

+8
source

Alternative way:

zip( mylist[:-1:2], mylist[1::2] )

Creates a list of tuples:

>>> zip(mylist[:-1:2],mylist[1::2])
[(1, 2), (3, 4), (5, 6)]

If you really need a list of lists:

map(list, zip(mylist[:-1:2],mylist[1::2]))
+6
source

Check out the "grouper" recipe from the itertools documentation :

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
+5
source

All Articles