Перейти к содержимому

Как запустить цикл for в обратном порядке python

  • автор:

PEP 322 – Reverse Iteration

This proposal is to add a builtin function to support reverse iteration over sequences.

Motivation

For indexable objects, current approaches for reverse iteration are error prone, unnatural, and not especially readable:

One other current approach involves reversing a list before iterating over it. That technique wastes computer cycles, memory, and lines of code:

Extended slicing is a third approach that minimizes the code overhead but does nothing for memory efficiency, beauty, or clarity.

Reverse iteration is much less common than forward iteration, but it does arise regularly in practice. See Real World Use Cases below.

Proposal

Add a builtin function called reversed() that makes a reverse iterator over sequence objects that support __getitem__() and __len__().

The above examples then simplify to:

The core idea is that the clearest, least error-prone way of specifying reverse iteration is to specify it in a forward direction and then say reversed.

The implementation could be as simple as:

No language syntax changes are needed. The proposal is fully backwards compatible.

A C implementation and unit tests are at: https://bugs.python.org/issue834422

BDFL Pronouncement

This PEP has been conditionally accepted for Py2.4. The condition means that if the function is found to be useless, it can be removed before Py2.4b1.

Alternative Method Names

  • reviter – Jeremy Fincher’s suggestion matches use of iter()
  • ireverse – uses the itertools naming convention
  • inreverse – no one seems to like this one except me

The name reverse is not a candidate because it duplicates the name of the list.reverse() which mutates the underlying list.

Discussion

The case against adoption of the PEP is a desire to keep the number of builtin functions small. This needs to weighed against the simplicity and convenience of having it as builtin instead of being tucked away in some other namespace.

Real World Use Cases

Here are some instances of reverse iteration taken from the standard library and comments on why reverse iteration was necessary:

In this application popping is required, so the new function would not help.

The need for reverse iteration arises because the tail of the underlying list is altered during iteration.

The need for reverse iteration arises because the tail of the underlying list is altered during iteration.

Rejected Alternatives

Several variants were submitted that attempted to apply reversed() to all iterables by running the iterable to completion, saving the results, and then returning a reverse iterator over the results. While satisfying some notions of full generality, running the input to the end is contrary to the purpose of using iterators in the first place. Also, a small disaster ensues if the underlying iterator is infinite.

Putting the function in another module or attaching it to a type object is not being considered. Like its cousins, zip() and enumerate(), the function needs to be directly accessible in daily programming. Each solves a basic looping problem: lock-step iteration, loop counting, and reverse iteration. Requiring some form of dotted access would interfere with their simplicity, daily utility, and accessibility. They are core looping constructs, independent of any one application domain.

Использование цикла for в Python

Эффективное использование цикла for в Python

В этой статье вы узнаете, как более эффективно использовать цикл for в различных ситуациях.

Введение

В языке программирования Python есть два цикла while и for. Давайте посмотрим как использовать второй.

Перебор двух списков

Возможно, вы захотите выполнить итерацию одновременно по двум спискам или последовательностям.

Этого можно добиться с помощью функции zip().

Вывод программы

Использование функции enumerate

Во время прохождения цикла for через последовательность (списки, кортеж и строки) индекс элемента и его значение могут быть получены с помощью функции enumerate.

Вывод программы

Функция enumerate() возвращает элементы списка с их индексами.

Просмотр словаря с помощью метода items

Мы можем получить как ключи, так и соответствующие им значения при наведении курсора на словарь с помощью метода items().

Вывод программы

Обратный перебор цикла

Чтобы пробежаться циклом по диапазону чисел в обратном порядке, сначала укажите диапазон, а затем вызовите функцию reversed().

Вывод программы

Та же самая аналогия применяется и к спискам:

Вывод программы

Заключение

Сегодня мы рассмотрели как используется цикл for в Python. Если у вас есть дополнительные вопросы, не стесняйтесь задавать их в комментариях.

Программирую на Python с 2017 года. Люблю создавать контент, который помогает людям понять сложные вещи. Не представляю жизнь без непрерывного цикла обучения, спорта и чувства юмора.

Reverse for loop in Python | Example code

To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function.

Example Reverse for loop in Python

Simple example code:

Using reversed() function

A code demonstrates how to backward iteration is done with reversed() function on the for-loop.

Output:

Reverse for loop in Python

Using range() Function

range() and xrange() take a third parameter that specifies a step. So you can do the following.

Output: Thu Wed Tue Mon

Python’s foreach backward Example

Use built-in reversed() function.

Output:

Note: Python 3 has not separate range and xrange functions, there is just range , which follows the design of Python 2’s xrange .

Do comment if you have any doubts and suggestions on this Python loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

Итерация списка в Python в обратном направлении

Итерация списка в Python в обратном направлении

В этом руководстве будут рассмотрены различные методы, доступные для обхода списка в обратном порядке в Python.

Please enable JavaScript

Используйте функцию reversed() для обхода списка в обратном порядке в Python

Мы можем перемещаться по списку в Python в обратном порядке, используя встроенную функцию reversed() . Функция reversed() возвращает обратную итерацию последовательности, предоставленной в качестве входных данных.

Функция reversed() принимает единственный параметр, который представляет собой обратную последовательность. Последовательность может быть кортежем, строкой, списком, диапазоном и т. Д.

Однако, чтобы также получить доступ к исходному индексу последовательности, мы можем дополнительно использовать функцию enumerate() в нашем списке, прежде чем передавать ее в функцию reversed() .

См. Следующий код.

Следовательно, мы получаем результат с исходным индексом последовательности. Однако стоит отметить, что enumerate() возвращает генератор, и генераторы не могут быть отменены. Поэтому очень важно сначала преобразовать его в список.

Используйте функцию range() для обхода списка в обратном порядке в Python

Другой метод обхода последовательности в обратном порядке в Python — использование доступной функции range .

Функция range , доступная в Python, возвращает последовательность чисел, начиная с 0 по умолчанию, которая автоматически увеличивается на дополнительную 1 (по умолчанию).

Функция range принимает три разных параметра — start (необязательно), stop (обязательно), step (необязательно). Все три параметра принимают на вход целое число.

См. Следующий код.

Следовательно, как показано выше, мы можем пройти последовательность в обратном порядке с исходным индексом последовательности.

Используйте цикл for для обхода списка в обратном порядке в Python

Мы можем перемещаться по списку в обратном порядке в Python, используя цикл for . Он выполняет итерацию по последовательности, которая может быть списком, кортежем, строкой и т. Д.

Мы можем использовать его для просмотра списка в обратном порядке, как показано ниже.

Обратите внимание, что [::-1] в приведенном выше коде только нарезает список в обратном порядке только для цикла. Следовательно, он не изменяет и не модифицирует массив данных или список, предоставляемый постоянно.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *