Welcome, guest | Sign In | My Account | Store | Cart
```def reshape(seq, how):
"""Reshape the sequence according to the template in ``how``.
>>> seq = range(1, 9)
>>> reshape(seq, [4]) # lists of 4
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> reshape(seq, (4,)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2,2)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2,[2])) # (i, i, [i, i])
[(1, 2, [3, 4]), (5, 6, [7, 8])]
>>> reshape(seq, ((2,),[2])) # etc....
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
>>> reshape(seq, (1,[2],1))
[(1, [2, 3], 4), (5, [6, 7], 8)]
>>> reshape(tuple(seq), ([[1],1,(2,)],))
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
>>> reshape(tuple(seq), ([1],1,(2,)))
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
"""
def flatten(seq):
rv = []
for s in seq:
if type(s) in (list, tuple):
rv.extend(flatten(s))
else:
rv.append(s)
return rv
i = 0
f = type(how)
rv = [None]*(len(seq)//sum(flatten(how)))
for k in range(len(rv)):
rv[k] = []
for gi in g:
if type(gi) is int:
rv[k].extend(seq[i: i + gi])
i += gi
else:
n = sum(flatten(gi))
fg = type(gi)
rv[k].append(fg(reshape(seq[i: i + n], gi))[0])
i += n
rv[k] = f(rv[k])
return type(seq)(rv)
```