List transpose method
gh_pythonlist at gmx.de
Thu Nov 1 22:41:04 CET 2001
On Thu, Nov 01, 2001 at 10:12:16PM +0100, Gerhard Häring wrote:
> On Fri, Nov 02, 2001 at 08:42:23AM +1100, Tom Harris wrote:
> > Hi,
> > Suppose I have a list like ((1,2), (3,4), (5,6)). Can some functional guru
> > tell me a one liner to transpose this to the form ((1,3,5),(2,4,6))? I can
> > only come up with an ugly multiliner.
> I guess any single-liner will be obfuscated Python and not necessarily
> any more efficient.
> If you need such things often, I'd suggest you take a look at Numeric
> Python. It contains many functions for matrices.
> Interesting problem nevertheless ...
This is my ugly version with list comprehensions. I'm looking forward to
seeing better ones :-)
# Fun with list comprehensions
n = len(m)
return [[m[j][i] for i in range(len(m)) for j in range(n)][k*n:k*n+n] for k in range(len(m))]
l = ((1,2), (3,4), (5,6))
mail: gerhard <at> bigfoot <dot> de registered Linux user #64239
web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20 A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))
More information about the Python-list