PencilCrate PencilCrate - 7 months ago 18
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]]


to

[[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:
newList.append(subList[0])
print(newList)

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

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)]
Comments