interchanging rows and columns

Johannes Zellner johannes at zellner.org
Sat Oct 14 10:28:23 EDT 2000


In article <8s9mhl0o52 at news2.newsguy.com>, Alex Martelli wrote:
>"Ruud de Rooij" <*@spam.ruud.org> wrote in message
>news:87lmvr3eo9.fsf at hobbes.home.ruud.org...
>> johannes at zellner.org (Johannes Zellner) writes:
>>
>> > how can I turn
>> >    [[1, 2, 3], [4, 5, 6]]
>> > into
>> >    [[1, 4], [2, 5], [3, 6]]
>>
>> The pythonic way to do these things seems to be to simply write a
>> nested for loop, something like this:
>>
>> def transpose(m):
>>   n = []
>>   for i in range(len(m[0])):
>>     r = []
>>     for j in range(len(m)):
>>       r.append(m[j][i])
>>     n.append(r)
>>   return n
>
>Fine, but, in 2.0, an alternative...:
>
>    def transpose(m):
>        return [ [ subm[i] for subm in m ] for i in range(len(m[0])) ]
>
hmm. I also found a solution myself:

    apply(lambda *x: map(None, *x), my_matrix)

It seems that one can really write unreadable code with python :-(

-- 
   Johannes



More information about the Python-list mailing list