pythonlistsplittuples

Splitting a long tuple into smaller tuples


I have a long tuple like

(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)

and i am trying to split it into a tuple of tuples like

((2, 2, 10, 10), (344, 344, 45, 43), (2, 2, 10, 10), (12, 8, 2, 10))

I am new to python and am not very good with tuples o(2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)r lists. My friend said i should split it but i just cant get it -_-

I need to split the tuple into tuples with 4 elements that i will later use a rectangles to draw to a image with PIL.


Solution

  • Well there is a certain idiom for that:

    def grouper(n, iterable):
        args = [iter(iterable)] * n
        return zip(*args)
    
    t = (2, 2, 10, 10, 344, 344, 45, 43, 2, 2, 10, 10, 12, 8, 2, 10)
    print grouper(4, t)
    

    But its kind of complicated to explain. A slightly more general version of this is listed in the itertools receipes.

    You can also slice the tuple yourself

    parts = (t[0:4], t[4:8], t[8:12], t[12:16])
    
    # or as a function
    def grouper2(n, lst):
        return [t[i:i+n] for i in range(0, len(t), n)]
    

    which is probably what your friend meant.