0

I have a list

L = [1, 2, 3, 4...]

which have n*3 elements. I want to be able to do something like

for a, b, c in three_tuple_split(L)

in a pythonic way but can't come up with one.

jamylak
  • 128,818
  • 30
  • 231
  • 230
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
  • 3
    This has to be a dupe ... – mgilson Apr 03 '13 at 13:17
  • 5
    And it is! http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python – mgilson Apr 03 '13 at 13:17
  • @mgilson Not this is not, here, the aim is to split the list into 3 (or n) equally sized parts, not of size n, but of size len(l)//n. – pradyunsg Apr 04 '13 at 08:53
  • @Schoolboy -- I don't think so. If that was the case, OP would say that they wanted `a,b,c = three_tuple_split(L)` without the loop. – mgilson Apr 04 '13 at 10:01

3 Answers3

3

Inefficient but pythonic solution:

for a, b, c in zip(*[iter(seq)]*3): pass

For a more efficient implementation, look at the itertools grouper recipe:

from itertools import izip_longest

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)

for a, b, c in grouper(3, seq):
    pass
jamylak
  • 128,818
  • 30
  • 231
  • 230
0
#!/usr/bin/env python
mylist = range(21)
def three_tuple_split(l):
    if len(l)%3 != 0:
        raise Exception('bad len')
    for i in xrange(0,len(l),3):
        yield l[i:i+3]
for a,b,c in three_tuple_split(mylist):
    print a,b,c
Hal Canary
  • 2,154
  • 17
  • 17
0

Just use slices and a for loop.

def break_into_chunks(l,n):
    x = len(l)
    step = x//n
    return [l[i:i+step] for i in range(0,x,step)]

Or a slower one:

def break_into_chunks(l,n):
    return [l[i:i+len(l)//n] for i in range(0,len(l),len(l)//n)]

To use:

for a, b, c in break_into_chunks(L,3):
pradyunsg
  • 18,287
  • 11
  • 43
  • 96