-2

I need to split a list like:

m=[[1,2,3,4,5,6,7,8,9,0],[11,12,13,14,15,16,17,18,19,20],[21,22,23,24,25,26,27,28,29,30],[31,32,33,34,35,36,37,38,39,40],[41,42,43,44,45,46,47,48,49,50],[51,52,53,54,55,56,57,58,59,60],[61,62,63,64,65,66,67,68,69,70],[71,72,73,74,75,76,77,78,79,80],[81,82,83,84,85,86,87,88,89,90],[91,92,93,94,95,96,97,98,99,100],

into smaller 5x5 lists like:

m1=[[1,2,3,4,5],[11,12,13,14,15],[21,22,23,24,25],[31,32,33,34,35],[41,42,43,44,45]]
m2=[[6,7,8,9,0],[16,17,18,19,20],[26,27,28,29,30],[36,37,38,39,40],[46,47,48,49,50]]

and have a new list that contains these smaller lists:

new_list=[m1,m2,m3,m4]

thanks

  • 1
    possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – fredtantini Oct 20 '14 at 20:31
  • 1
    You can use [`numpy.reshape`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) – Cory Kramer Oct 20 '14 at 20:31
  • @fredtantini: That only provides part of the answer; he has a list of lists, and needs to split each one into evenly-sized chunks, and split those lists of chunks out into separate lists. – abarnert Oct 20 '14 at 20:39

1 Answers1

0

First, how can you split a list of 10 elements into two lists of 5 elements?

def split_list(m):
    return m[:len(m)//2], m[len(m)//2:]

Now, we want to map that over each list in m:

mm = [split_list(sublist) for sublist in m]

But now we have a list of pairs of lists, not a pair of lists of lists. How do you fix that? zip is the answer: it turns an X of Y of foo into a Y of X of foo:

new_list = list(zip(*mm))

If you don't like the fact that this gives you a list of tuples of lists instead of a list of lists of lists, just use a list comprehension with the list function:

new_list = [list(m) for m in zip(*mm)]

If you want to change it to split any list into N/5 groups of 5, instead of 2 groups of N/2, that's just a matter of changing the first function. A general-purpose grouper function will do that, like the one from the itertools recipes (or see this question for other options, if you prefer):

def grouper(iterable, n=5):
    args = [iter(iterable)] * n
    return itertools.izip_longest(*args)

So:

new_list = [list(mm) for mm in zip(*grouper(m, 5))]
Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671