How to rotate a matrix (nested list) counter clockwise by 90 degrees











up vote
4
down vote

favorite












I'm trying to rotate a matrix counter clockwise by 90 degrees.
For example, if:



m = [[1,2,3],
[2,3,3],
[5,4,3]]


then the result should be



m = [[3,3,3],
[2,3,4],
[1,2,5]]


So far, I found:



rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
for row in rez:
print(row)


This gives me



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


This is close, but the rows would need to be reverses. Does anyone know a simple way to rotate this matrix counter clockwise by 90 degrees?










share|improve this question






















  • Here you do not rotate, you transpose.
    – Willem Van Onsem
    Nov 12 at 20:34










  • You can here use numpy with np.rot90(m).
    – Willem Van Onsem
    Nov 12 at 20:35






  • 1




    list(zip(*m))[::-1]
    – Warren Weckesser
    Nov 12 at 20:44















up vote
4
down vote

favorite












I'm trying to rotate a matrix counter clockwise by 90 degrees.
For example, if:



m = [[1,2,3],
[2,3,3],
[5,4,3]]


then the result should be



m = [[3,3,3],
[2,3,4],
[1,2,5]]


So far, I found:



rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
for row in rez:
print(row)


This gives me



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


This is close, but the rows would need to be reverses. Does anyone know a simple way to rotate this matrix counter clockwise by 90 degrees?










share|improve this question






















  • Here you do not rotate, you transpose.
    – Willem Van Onsem
    Nov 12 at 20:34










  • You can here use numpy with np.rot90(m).
    – Willem Van Onsem
    Nov 12 at 20:35






  • 1




    list(zip(*m))[::-1]
    – Warren Weckesser
    Nov 12 at 20:44













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I'm trying to rotate a matrix counter clockwise by 90 degrees.
For example, if:



m = [[1,2,3],
[2,3,3],
[5,4,3]]


then the result should be



m = [[3,3,3],
[2,3,4],
[1,2,5]]


So far, I found:



rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
for row in rez:
print(row)


This gives me



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


This is close, but the rows would need to be reverses. Does anyone know a simple way to rotate this matrix counter clockwise by 90 degrees?










share|improve this question













I'm trying to rotate a matrix counter clockwise by 90 degrees.
For example, if:



m = [[1,2,3],
[2,3,3],
[5,4,3]]


then the result should be



m = [[3,3,3],
[2,3,4],
[1,2,5]]


So far, I found:



rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
for row in rez:
print(row)


This gives me



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


This is close, but the rows would need to be reverses. Does anyone know a simple way to rotate this matrix counter clockwise by 90 degrees?







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 at 20:33







user10642683



















  • Here you do not rotate, you transpose.
    – Willem Van Onsem
    Nov 12 at 20:34










  • You can here use numpy with np.rot90(m).
    – Willem Van Onsem
    Nov 12 at 20:35






  • 1




    list(zip(*m))[::-1]
    – Warren Weckesser
    Nov 12 at 20:44


















  • Here you do not rotate, you transpose.
    – Willem Van Onsem
    Nov 12 at 20:34










  • You can here use numpy with np.rot90(m).
    – Willem Van Onsem
    Nov 12 at 20:35






  • 1




    list(zip(*m))[::-1]
    – Warren Weckesser
    Nov 12 at 20:44
















Here you do not rotate, you transpose.
– Willem Van Onsem
Nov 12 at 20:34




Here you do not rotate, you transpose.
– Willem Van Onsem
Nov 12 at 20:34












You can here use numpy with np.rot90(m).
– Willem Van Onsem
Nov 12 at 20:35




You can here use numpy with np.rot90(m).
– Willem Van Onsem
Nov 12 at 20:35




1




1




list(zip(*m))[::-1]
– Warren Weckesser
Nov 12 at 20:44




list(zip(*m))[::-1]
– Warren Weckesser
Nov 12 at 20:44












3 Answers
3






active

oldest

votes

















up vote
2
down vote













You could do the following:



m = [[1, 2, 3],
[2, 3, 3],
[5, 4, 3]]

result = list(map(list, zip(*m)))[::-1]

print(result)


Output



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


With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(...)[::-1] you convert that iterable into a list and reverse it.






share|improve this answer






























    up vote
    0
    down vote













    What you here basically do is map a matrix A to a matrix B such that:



    Bi j=Aj i



    In case you rotate elements, that means that if you rotate an n×m-matrix, then that means that:



    Bi j=Aj n-i



    So we can calculate this as:



    rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]


    which is thus the transpose, but than "reversed". Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.



    But that being said, numpy offers a numpy.rot90 function to rotate matrices:



    >>> np.rot90(m)
    array([[3, 3, 3],
    [2, 3, 4],
    [1, 2, 5]])





    share|improve this answer






























      up vote
      0
      down vote













      Other option is to use scipy.ndimage.rotate




      Rotate an array.



      The array is rotated in the plane defined by the two axes given by the
      axes parameter using spline interpolation of the requested order.




      import numpy as np
      from scipy import ndimage

      m = np.matrix([[1,2,3],
      [2,3,3],
      [5,4,3]])

      ndimage.rotate(m, 90.0) #angle as float.



      Out: 
      array([[3, 3, 3],
      [2, 3, 4],
      [1, 2, 5]])






      Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :




      matrix = [[1, 2, 3],
      [2, 3, 3],
      [5, 4, 3]]

      np.matrix(list(zip(*matrix)))[::-1]



      Out: 
      matrix([[3, 3, 3],
      [2, 3, 4],
      [1, 2, 5]])






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269685%2fhow-to-rotate-a-matrix-nested-list-counter-clockwise-by-90-degrees%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown
























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        2
        down vote













        You could do the following:



        m = [[1, 2, 3],
        [2, 3, 3],
        [5, 4, 3]]

        result = list(map(list, zip(*m)))[::-1]

        print(result)


        Output



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


        With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(...)[::-1] you convert that iterable into a list and reverse it.






        share|improve this answer



























          up vote
          2
          down vote













          You could do the following:



          m = [[1, 2, 3],
          [2, 3, 3],
          [5, 4, 3]]

          result = list(map(list, zip(*m)))[::-1]

          print(result)


          Output



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


          With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(...)[::-1] you convert that iterable into a list and reverse it.






          share|improve this answer

























            up vote
            2
            down vote










            up vote
            2
            down vote









            You could do the following:



            m = [[1, 2, 3],
            [2, 3, 3],
            [5, 4, 3]]

            result = list(map(list, zip(*m)))[::-1]

            print(result)


            Output



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


            With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(...)[::-1] you convert that iterable into a list and reverse it.






            share|improve this answer














            You could do the following:



            m = [[1, 2, 3],
            [2, 3, 3],
            [5, 4, 3]]

            result = list(map(list, zip(*m)))[::-1]

            print(result)


            Output



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


            With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(...)[::-1] you convert that iterable into a list and reverse it.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 12 at 20:41









            jhpratt

            3,07582232




            3,07582232










            answered Nov 12 at 20:38









            Daniel Mesejo

            11.2k1924




            11.2k1924
























                up vote
                0
                down vote













                What you here basically do is map a matrix A to a matrix B such that:



                Bi j=Aj i



                In case you rotate elements, that means that if you rotate an n×m-matrix, then that means that:



                Bi j=Aj n-i



                So we can calculate this as:



                rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]


                which is thus the transpose, but than "reversed". Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.



                But that being said, numpy offers a numpy.rot90 function to rotate matrices:



                >>> np.rot90(m)
                array([[3, 3, 3],
                [2, 3, 4],
                [1, 2, 5]])





                share|improve this answer



























                  up vote
                  0
                  down vote













                  What you here basically do is map a matrix A to a matrix B such that:



                  Bi j=Aj i



                  In case you rotate elements, that means that if you rotate an n×m-matrix, then that means that:



                  Bi j=Aj n-i



                  So we can calculate this as:



                  rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]


                  which is thus the transpose, but than "reversed". Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.



                  But that being said, numpy offers a numpy.rot90 function to rotate matrices:



                  >>> np.rot90(m)
                  array([[3, 3, 3],
                  [2, 3, 4],
                  [1, 2, 5]])





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    What you here basically do is map a matrix A to a matrix B such that:



                    Bi j=Aj i



                    In case you rotate elements, that means that if you rotate an n×m-matrix, then that means that:



                    Bi j=Aj n-i



                    So we can calculate this as:



                    rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]


                    which is thus the transpose, but than "reversed". Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.



                    But that being said, numpy offers a numpy.rot90 function to rotate matrices:



                    >>> np.rot90(m)
                    array([[3, 3, 3],
                    [2, 3, 4],
                    [1, 2, 5]])





                    share|improve this answer














                    What you here basically do is map a matrix A to a matrix B such that:



                    Bi j=Aj i



                    In case you rotate elements, that means that if you rotate an n×m-matrix, then that means that:



                    Bi j=Aj n-i



                    So we can calculate this as:



                    rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]


                    which is thus the transpose, but than "reversed". Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.



                    But that being said, numpy offers a numpy.rot90 function to rotate matrices:



                    >>> np.rot90(m)
                    array([[3, 3, 3],
                    [2, 3, 4],
                    [1, 2, 5]])






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 12 at 20:47

























                    answered Nov 12 at 20:42









                    Willem Van Onsem

                    142k16135227




                    142k16135227






















                        up vote
                        0
                        down vote













                        Other option is to use scipy.ndimage.rotate




                        Rotate an array.



                        The array is rotated in the plane defined by the two axes given by the
                        axes parameter using spline interpolation of the requested order.




                        import numpy as np
                        from scipy import ndimage

                        m = np.matrix([[1,2,3],
                        [2,3,3],
                        [5,4,3]])

                        ndimage.rotate(m, 90.0) #angle as float.



                        Out: 
                        array([[3, 3, 3],
                        [2, 3, 4],
                        [1, 2, 5]])






                        Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :




                        matrix = [[1, 2, 3],
                        [2, 3, 3],
                        [5, 4, 3]]

                        np.matrix(list(zip(*matrix)))[::-1]



                        Out: 
                        matrix([[3, 3, 3],
                        [2, 3, 4],
                        [1, 2, 5]])






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          Other option is to use scipy.ndimage.rotate




                          Rotate an array.



                          The array is rotated in the plane defined by the two axes given by the
                          axes parameter using spline interpolation of the requested order.




                          import numpy as np
                          from scipy import ndimage

                          m = np.matrix([[1,2,3],
                          [2,3,3],
                          [5,4,3]])

                          ndimage.rotate(m, 90.0) #angle as float.



                          Out: 
                          array([[3, 3, 3],
                          [2, 3, 4],
                          [1, 2, 5]])






                          Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :




                          matrix = [[1, 2, 3],
                          [2, 3, 3],
                          [5, 4, 3]]

                          np.matrix(list(zip(*matrix)))[::-1]



                          Out: 
                          matrix([[3, 3, 3],
                          [2, 3, 4],
                          [1, 2, 5]])






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Other option is to use scipy.ndimage.rotate




                            Rotate an array.



                            The array is rotated in the plane defined by the two axes given by the
                            axes parameter using spline interpolation of the requested order.




                            import numpy as np
                            from scipy import ndimage

                            m = np.matrix([[1,2,3],
                            [2,3,3],
                            [5,4,3]])

                            ndimage.rotate(m, 90.0) #angle as float.



                            Out: 
                            array([[3, 3, 3],
                            [2, 3, 4],
                            [1, 2, 5]])






                            Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :




                            matrix = [[1, 2, 3],
                            [2, 3, 3],
                            [5, 4, 3]]

                            np.matrix(list(zip(*matrix)))[::-1]



                            Out: 
                            matrix([[3, 3, 3],
                            [2, 3, 4],
                            [1, 2, 5]])






                            share|improve this answer














                            Other option is to use scipy.ndimage.rotate




                            Rotate an array.



                            The array is rotated in the plane defined by the two axes given by the
                            axes parameter using spline interpolation of the requested order.




                            import numpy as np
                            from scipy import ndimage

                            m = np.matrix([[1,2,3],
                            [2,3,3],
                            [5,4,3]])

                            ndimage.rotate(m, 90.0) #angle as float.



                            Out: 
                            array([[3, 3, 3],
                            [2, 3, 4],
                            [1, 2, 5]])






                            Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :




                            matrix = [[1, 2, 3],
                            [2, 3, 3],
                            [5, 4, 3]]

                            np.matrix(list(zip(*matrix)))[::-1]



                            Out: 
                            matrix([[3, 3, 3],
                            [2, 3, 4],
                            [1, 2, 5]])







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 13 at 5:02

























                            answered Nov 12 at 20:57









                            n1tk

                            1,09121226




                            1,09121226






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269685%2fhow-to-rotate-a-matrix-nested-list-counter-clockwise-by-90-degrees%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Guess what letter conforming each word

                                Port of Spain

                                Run scheduled task as local user group (not BUILTIN)