List transpose method

Emile van Sebille emile at fenx.com
Thu Nov 1 17:21:42 EST 2001


"Tom Harris" <TomH at optiscan.com> wrote in message
news:mailman.1004650983.10335.python-list at python.org...
> 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.
>
>


If you don't need to be flexible,
r = ((s[0][0], s[1][0], s[2][0]), (s[0][1], s[1][1], s[2][1]))

otherwise,

def transpose(s):
    return tuple([tuple([s[i][j] for i in range(len(s))]) for j in
range(len(s[0]))])

s = ((1,2,12), (3,4,34), (5,6,56), (7,8,78))

print transpose(s)

seems to do it.

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list