Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 2D to 1D list in clockwise direction?

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 ??

like image 950
Mohammad Zain Abbas Avatar asked Jul 05 '26 15:07

Mohammad Zain Abbas


1 Answers

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)))
like image 52
Jack Evans Avatar answered Jul 07 '26 05:07

Jack Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!