PencilCrate PencilCrate - 2 years ago 121
Python Question

How to output a multidimensional list with Python

I am trying to convert this first multidimensional array to the second one:

[[1,4,7], [3,6,2], [2,5,9], [88,6,1]]


[[88,2,3,1], [6,5,6,4], [1,9,2,7]]

I wrote this function

def rotate(myList):
newList = []
reverseList = list(reversed(myList))
for subList in reverseList:

rotate([[1,4,7], [3,6,2], [2,5,9], [88,6,1]])

This outputs

[88, 2, 3, 1]

I reverse the multidimensional list, and for each sublist in the reversed multidimensional list, I append the first element to a new list called newList.

This is a good start, but it is not complete. How would one output the rest of the lists? I don't know how to output multiple lists to a new multidimensional list in this context.

Answer Source

zip() is your friend.

def rotate(mylist):
    return list(zip(*mylist[::-1]))

This reverses mylist, sends each sublist to zip(), and turns that into a list.

>>> rotate([[1,4,7], [3,6,2], [2,5,9], [88,6,1]])
[(88, 2, 3, 1), (6, 5, 6, 4), (1, 9, 2, 7)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download