How to make the rotation of the matrix in one line without numpy and cycles?

For example, if the original matrix

[[1, 2], [3, 4]] 

then the resultant should be:

 [[3, 1], [4, 2]] 
  • 3
    First, it does not matter. Secondly, it could be arranged as a translation of the original with a question and an answer. Third, I suppose it slows down :) - andreymal
  • Related question: Matrix Transpose in Python - jfs
  • This question should be closed, because it is not a question. - user194374
  • @kff should be simply split into two parts: "how to turn" (question), "one way to do this, with an explanation" (answer). The answer, of course, is in the answer form. This is clearly welcome . For example, how I did here - jfs

2 answers 2

Quite a working option if the speed is not critical.

But if there are requirements for processing speed, it is better to use NumPy.

Performance comparison for 100x100 array:

 In [72]: a = np.random.randint(0, 99, (100, 100)) In [73]: m = a.tolist() In [74]: a.shape Out[74]: (100, 100) In [75]: %timeit tuple(zip(*m[::-1])) 10000 loops, best of 3: 71 µs per loop In [76]: %timeit np.rot90(a, 3) The slowest run took 9.64 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.63 µs per loop 

Performance comparison for 1000x1000 array:

 In [77]: a = np.random.randint(0, 99, (1000, 1000)) In [78]: m = a.tolist() In [79]: a.shape Out[79]: (1000, 1000) In [80]: %timeit tuple(zip(*m[::-1])) 10 loops, best of 3: 32.6 ms per loop In [81]: %timeit np.rot90(a, 3) The slowest run took 7.54 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.59 µs per loop 

Performance comparison for an array of 10000x10000:

 In [82]: a = np.random.randint(0, 99, (10000, 10000)) In [83]: m = a.tolist() In [84]: a.shape Out[84]: (10000, 10000) In [85]: %timeit tuple(zip(*m[::-1])) 1 loop, best of 3: 4.43 s per loop In [86]: %timeit np.rot90(a, 3) The slowest run took 11.29 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.59 µs per loop 

    I found a rather elegant way to turn the matrix into one line without numpy and cycles. I couldn’t find anything sensible in runet, maybe someone can help. Original here: Link to original

     rotated = zip(*original[::-1]) # Python 2 rotated = tuple(zip(*original[::-1])) # Python 3 

    How it works.

     original = [[1, 2], [3, 4]] 

    Reverse works first

      >>> original[::-1] [[3, 4], [1, 2]] 

    And then this already wrapped list is passed to the zip() function.

     zip([3, 4], [1, 2]) # ^ ^----column 2 # |-------column 1 

    I hope someone will come in handy, and then they start going through the built-in loops, etc.