This function takes a list and pulls it apart into a user-defined number of pieces. It acts like a sort of reverse zip function (although it deals with only the very simplest cases).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
def unzip(p, n): """Split a list-like object, 'p', into 'n' sub-lists by taking the next unused element of the main list and adding it to the next sub-list. A list of tuples (the sub-lists) is returned. Each of the sub-lists is of the same length; if p%n != 0, the shorter sub-lists are padded with 'None'. Example: >>> unzip(['a','b','c','d','e'], 3) [('a', 'd'), ('b', 'e'), ('c', None)] """ (mlen, lft) = divmod(len(p),n) # find length of longest sub-list if lft != 0: mlen += 1 lst = [[None]*mlen for i in range(n)] # initialize list of lists for i in range(len(p)): (j, k) = divmod(i, n) lst[k][j] = p[i] return map(tuple, lst)
This recipe was useful to me recently when I had to take a Python list and break it down into a number of different pieces, putting each consecutive item of the list into a separate sub-list.