I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.
For example:
When n = 3
list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]
or
list = [[2, 3, 5]
,[8, 7, 1]
,[0, 4, 6]]
would become
result = [2, 3, 5, 1, 6, 4, 0, 8, 7]
and when n = 5
list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]
or
list = [[ 2, 3, 5, 9, 10]
,[ 8, 7, 1, 11, 13]
,[ 0, 4, 6, 21, 22]
,[ 12, 19, 17, 18, 25]
, [ 14, 15, 16, 23, 24]]
would become
result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]
How can I efficiently do that for any value of nxn ??
Adapted from Print two-dimensional array in spiral order
import itertools
arr = [[2, 3, 5, 9, 10],
[8, 7, 1, 11, 13],
[0, 4, 6, 21, 22],
[12, 19, 17, 18, 25],
[14, 15, 16, 23, 24]]
def transpose_and_yield_top(arr):
while arr:
yield arr[0]
arr = list(zip(*arr[1:]))[::-1]
rotated = list(itertools.chain(*transpose_and_yield_top(arr)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With