Inverse of zip
1 2 3 4 5 6 7 8 9 10 11 12 13 | def unzip(args):
"""
inverse of zip. Given: ((1,"a"),(2,"b")) --> ((1,2),("a","b"))
seq == unzip(zip(seq)) if seq is a rectangular matrix (all of its row has the same length.
"""
result = []
n = min(map(len,args))
for i in range(n):result.append([])
for i in range(len(args)):
for j in range(n):
result[j].append(args[i][j])
return tuple(result)
|
Tags: algorithms
unzip. A shorter version of unzip can be:
or for older Python versions:
Why isn't this standard? This is very useful; I don't see why it isn't in the python standard library. When I'm doing heavy list manipulations this is extremely handy.
PEP anyone?
isn't zip its own inverse? >>> zip((1, 2), ('a', 'b'))
[(1, 'a'), (2, 'b')]
[(1, 2), ('a', 'b')]
Why do we need an unzip?
Thanks,
-- sudhir
Simple unzip. unzip = lambda ll: apply (zip, ll)
such unzip is actually a matrix transposer;
also unzip (unzip (ll)) == ll
Another unzip. def unzip(seq): return zip(*seq)
Zip is not its own inverse. Zip isn't its own inverse in general, e.g.,
Redundancy. I just realized that this is equivalent to the first lambda expression on the top. Oh, well. It's redundant, but to my eye it looks more Pythonic.
Feed zip arguments correctly.