Как повернуть матрицу на 90 градусов python

от admin

numpy.rot90

Функция rot90() поворачивает массив на 90 градусов в плоскости указанных осей, при этом сам поворот осуществляется в направлении от первой оси ко второй.

Параметры: a — подобный массиву объект Массив NumPy или любой объект который может быть преобразован в массив NumPy, при этом входной массив должен иметь не менее двух измерений. k — целое число (необязательный) Определяет количество поворотов, k = 1 (по умолчанию) соответствует повороту на 90 градусов, k = 2 соответствует 180 градусам и т.д. axes — подобный массиву объект (необязательный) Последовательность из двух целых чисел — номеров осей которые определяют плоскость вращения. Числа (оси) должны быть разными. По умолчанию axes = (0, 1) Возвращает: ndarray — массив NumPy Представление повернутого массива a .

Замечание

Если указанные оси поменять местами то это изменит направление поворота, например, rot90(m, k = 1, axes = (1,0)) и rot90(m, k = 1, axes = (0,1)) будут вращать массив в разных направлениях. Использование в качестве параметра k отрицательных чисел так же изменит направление поворота на противоположное.

Как повернуть матрицу на 90 градусов python

Given a square matrix, turn it by 90 degrees in an anti-clockwise direction without using any extra space

Examples:

Input:
Matrix: 1 2 3
4 5 6
7 8 9

Output: 3 6 9
2 5 8
1 4 7

Input:
Matrix: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Output: 4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Note: An approach that requires extra space is already discussed here.

Example no1 – Inplace rotate square matrix by 90 degrees by forming cycles:

To solve the problem follow the below idea:

To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example,
A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row, and 1st column. The second cycle is formed by the 2nd row, second-last column, second-last row, and 2nd column. The idea is for each square cycle, to swap the elements involved with the corresponding cell in the matrix in an anti-clockwise direction i.e. from top to left, left to bottom, bottom to right, and from right to top one at a time using nothing but a temporary variable to achieve this

Dry run of the above approach:

First Cycle:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Moving first group of four elements (elements
of 1st row, last row, 1st column and last column) of first cycle
in counter clockwise.

4 2 3 16
5 6 7 8
9 10 11 12
1 14 15 13

Moving next group of four elements of
first cycle in counter clockwise

4 8 3 16
5 6 7 15
2 10 11 12
1 14 9 13

Moving final group of four elements of
first cycle in counter clockwise

4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13

Second Cycle:

4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13

Fixing second cycle

4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Rotating a two-dimensional array in Python

In a program I’m writing the need to rotate a two-dimensional array came up. Searching for the optimal solution I found this impressive one-liner that does the job:

I’m using it in my program now and it works as supposed. My problem though, is that I don’t understand how it works.

I’d appreciate if someone could explain how the different functions involved achieves the desired result.

8 Answers 8

That’s a clever bit.

First, as noted in a comment, in Python 3 zip() returns an iterator, so you need to enclose the whole thing in list() to get an actual list back out, so as of 2020 it’s actually:

Читать:
Код ошибки 91613 ccleaner что это

Here’s the breakdown:

  • [::-1] — makes a shallow copy of the original list in reverse order. Could also use reversed() which would produce a reverse iterator over the list rather than actually copying the list (more memory efficient).
  • * — makes each sublist in the original list a separate argument to zip() (i.e., unpacks the list)
  • zip() — takes one item from each argument and makes a list (well, a tuple) from those, and repeats until all the sublists are exhausted. This is where the transposition actually happens.
  • list() converts the output of zip() to a list.

So assuming you have this:

You first get this (shallow, reversed copy):

Next each of the sublists is passed as an argument to zip :

zip() repeatedly consumes one item from the beginning of each of its arguments and makes a tuple from it, until there are no more items, resulting in (after it’s converted to a list):

And Bob’s your uncle.

To answer @IkeMiguel’s question in a comment about rotating it in the other direction, it’s pretty straightforward: you just need to reverse both the sequences that go into zip and the result. The first can be achieved by removing the [::-1] and the second can be achieved by throwing a reversed() around the whole thing. Since reversed() returns an iterator over the list, we will need to put list() around that to convert it. With a couple extra list() calls to convert the iterators to an actual list. So:

We can simplify that a bit by using the "Martian smiley" slice rather than reversed() . then we don’t need the outer list() :

Of course, you could also simply rotate the list clockwise three times. 🙂

Русские Блоги

Python-двумерный массив для достижения поворота на 90 градусов

В этой статье рассказывается, как повернуть массив N * N на 90 градусов

Во-первых, определить одномерный массив очень просто:

Это письмо имеет тот же эффект, что и следующее письмо:

Итак, как создать двумерный массив следующим образом:

Если вы хотите быть более интуитивным, настройте его немного:

Далее надо повернуть массив на 90 градусов, поставить

Для достижения этой функции мы сначала разбиваем шаги на 3 шага:

код шоу, как показано ниже:

Перепечатано по адресу: https://www.cnblogs.com/nizhihong/p/8044023.html.

Интеллектуальная рекомендация

Меч относится к предложению + 43: количество N сиша + Java

Оригинальное название: бросить кубики на землю, все точки кости сталкиваются с точкой точки кости. Введите n, напечатали вероятность всех возможных значений. (6 сторон каждой кости, точки от 1 до 6) Р.

Введение в Python 4

функция ввода Использование функции Функция input () является функцией ввода. Функция input () — это функция ввода. Когда вы пишете вопрос в скобках функции, функция input () будет отображать вопрос в.

Основные операции в R 01

Повторите основную операцию секретной книги ниндзя языка R учителя Се Иихуэй.

Мастерство, создание американской легенды очистки воды

Мастера — это не только технические специалисты и квалифицированные мастера, которые могут решить некоторые практические проблемы в производстве и жизни, но также авангарды, которые могут руководить п.

курсы памяти Лу Feifei (а, понимать память понимания мозга)

Понимание памяти, что память? Понимание памяти, что память? 1 Понимание мозга 2 Что такое память Функция 3 Память 3.1 общие воспоминания путь 3.2 Факторы, влияющие на память 4 запоминающий материал Че.

Related Posts