What is the slickest way to transpose a square list of lists (tuple oftuples)?

C

Claudio Grondi

Gerard said:
My way is ugly. These has to be a better way.

Thanks,
Gerard
Ugly is not necessary not the slickest. To do better, there must be
something to compare to, right?

Claudio
 
D

Dave Hansen

My way is ugly. These has to be a better way.

This may not be the "slickest" way, but I needed some practice with
list comprehensions (I've never really gotten used to them...)

This works with lists. Making it work with tuples should be a simple
change. Also, it works for the general case of rectangular matrices
rather than being limited to squares.
"""
Transpose the rectangular two-dimentional matrix m.
"""
return [[m[y][x] for y in range(len(m))]for x in
range(len(m[0]))]
"""
Print the matrix m. Just to see the results.
"""
for row in m:
print row

td = [range(10) for x in range(10)]
pm(td)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
[3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
[6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
td2 = [range(10) for x in range(5)]
pm(td2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 0, 0, 0, 0]
[1, 1, 1, 1, 1]
[2, 2, 2, 2, 2]
[3, 3, 3, 3, 3]
[4, 4, 4, 4, 4]
[5, 5, 5, 5, 5]
[6, 6, 6, 6, 6]
[7, 7, 7, 7, 7]
[8, 8, 8, 8, 8]
[9, 9, 9, 9, 9]
Regards,
-=Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top