4

I want to split my list into rows that have all the same number of columns, I'm looking for the best (most elegant/pythonic) way to achieve this:

>>> split.split_size([1,2,3], 5, 0)
[[1, 2, 3, 0, 0]]

>>> split.split_size([1,2,3,4,5], 5, 0)
[[1, 2, 3, 4, 5]]

>>> split.split_size([1,2,3,4,5,6], 5, 0)
[[1, 2, 3, 4, 5], [6, 0, 0, 0, 0]]

>>> split.split_size([1,2,3,4,5,6,7], 5, 0)
[[1, 2, 3, 4, 5], [6, 7, 0, 0, 0]]

That's what I came up with so far:

def split_size(l, size, fillup):
    """
    splits list into chunks of defined size, fills up last chunk with fillup if below size
    """
    # len(l) % size or size
    # does i.e. size=5: 3->2, 4->1, 5->0
    stack = l + [fillup] * (size - (len(l) % size or size))
    result = []
    while len(stack) > 0:
        result.append(stack[:5])
        del stack[:5]
    return result

I'm sure there must be some smarter solutions. Especially for the "inverse mod" part: len(l) % size or size there must be a more readable way to do this, no?

hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Duplicate: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python – volting Sep 13 '10 at 19:30
  • possible duplicate of [What is the most "pythonic" way to iterate over a list in chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) – NullUserException Sep 13 '10 at 19:33
  • @Volting: I saw this other question, it's related but not the same because but I want to specify the size of each split. – hansaplast Sep 14 '10 at 07:04
  • @NullUserException: indeed the answer is the same, but the question isn't :-) – hansaplast Sep 14 '10 at 07:05

1 Answers1

6

The itertools recipe called grouper does what you want:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452