Przemierzaj listę w odwrotnej kolejności w Pythonie

Więc mogę zacząć od len(collection) i zakończyć na collection[0].

EDIT: Przepraszam, zapomniałem wspomnieć, że chcę również mieć dostęp do indeksu pętli.

Author: mtt2p, 2009-02-09

24 answers

Użyj wbudowanej funkcji reversed():

>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
...     print i
... 
baz
bar
foo

Aby uzyskać również dostęp do oryginalnego indeksu:

>>> for i, e in reversed(list(enumerate(a))):
...     print i, e
... 
2 baz
1 bar
0 foo
 850
Author: Greg Hewgill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-09 19:12:36

Możesz zrobić:

for item in my_list[::-1]:
    print item

(lub cokolwiek chcesz zrobić w pętli for.)

Plasterek [::-1] odwraca listę w pętli for (ale nie zmieni Twojej listy "na stałe").

 127
Author: mipadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-09 19:07:38

Jeśli potrzebujesz indeksu pętli, a nie chcesz przechodzić całą listę dwa razy, lub użyć dodatkowej pamięci, napiszę generator.

def reverse_enum(L):
   for index in reversed(xrange(len(L))):
      yield index, L[index]

L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
   print index, item
 57
Author: Triptych,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-10 17:23:20

Można to zrobić tak:

for i in range(len(collection)-1, -1, -1):
    print collection[i]

    # print(collection[i]) for python 3. +

Więc Twoje przypuszczenie było dość blisko :) trochę niezręczne, ale w zasadzie mówi: zacznij od 1 mniej niż len(collection), kontynuuj, aż dojdziesz do tuż przed -1, krokami -1.

Dla Twojej wiadomości, Funkcja help jest bardzo przydatna, ponieważ pozwala na przeglądanie dokumentów dla czegoś z konsoli Pythona, np:

help(range)

 43
Author: Alan Rowarth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-01 21:56:24

Wbudowana Funkcja reversed jest przydatna:

for item in reversed(sequence):

Dokumentacja dla odwróconych wyjaśnia jej ograniczenia.

Dla przypadków, w których muszę przejść sekwencję w odwrotnej kolejności wraz z indeksem (np. dla modyfikacji w miejscu zmieniających długość sekwencji), mam tę funkcję zdefiniowaną w module my codeutil:

import itertools
def reversed_enumerate(sequence):
    return itertools.izip(
        reversed(xrange(len(sequence))),
        reversed(sequence),
    )

Ten unika tworzenia kopii sekwencji. Oczywiście ograniczenia reversed nadal obowiązują.

 18
Author: tzot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-11 06:28:19
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

Lub

>>> print l[::-1]
['d', 'c', 'b', 'a']
 6
Author: Freddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-11 06:59:01

Może bez odtwarzania nowej listy, możesz to zrobić indeksując:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

Lub

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>
 4
Author: James Sapam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-15 05:04:53

Podoba mi się jednoliniowe podejście generatora:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))
 4
Author: lkraider,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-17 18:50:25

Użyj list.reverse(), a następnie iteruj tak, jak zwykle.

Http://docs.python.org/tutorial/datastructures.html

 2
Author: Bill Konrad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-09 09:51:36
def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)
 2
Author: Jase,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-25 01:27:05

Inne odpowiedzi są dobre, ale jeśli chcesz zrobić jak Styl rozumienia listy

collection = ['a','b','c']
[item for item in reversed( collection ) ]
 1
Author: fedmich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-27 15:17:43

Użyj wbudowanej funkcji reversed() dla obiektu sequence, ta metoda ma efekt wszystkich sekwencji

Bardziej szczegółowy odnośnik

 1
Author: lazybios,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-28 09:52:45

Możesz również użyć pętli while:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1
 1
Author: Yuval A.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-27 12:57:10

Proste podejście to:

for i in range(1,len(arr)+1):
    print(arr[-i])
 1
Author: ksooklall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-06 15:37:37

Jeśli to jest coś warte, możesz to zrobić tak. bardzo proste.

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]
 1
Author: emorphus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-27 17:18:28

Możesz użyć indeksu ujemnego w zwykłej pętli for:

>>> collection = ["ham", "spam", "eggs", "baked beans"]
>>> for i in range(1, len(collection) + 1):
...     print(collection[-i])
... 
baked beans
eggs
spam
ham

Aby uzyskać dostęp do indeksu tak, jakbyś iterował do przodu nad odwróconą kopią kolekcji, użyj i - 1:

>>> for i in range(1, len(collection) + 1):
...     print(i-1, collection[-i])
... 
0 baked beans
1 eggs
2 spam
3 ham

Aby uzyskać dostęp do oryginalnego, Nie odwróconego indeksu, użyj len(collection) - i:

>>> for i in range(1, len(collection) + 1):
...     print(len(collection)-i, collection[-i])
... 
3 baked beans
2 eggs
1 spam
0 ham
 1
Author: Malcolm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-26 03:15:41

Funkcja odwrotna przydaje się tutaj:

myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
    print x
 0
Author: bchhun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-09 19:07:30

Aby użyć indeksów ujemnych: zacznij od -1 i Cofnij o -1 przy każdej iteracji.

>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
...     print i, a[i]
... 
-1 baz
-2 bar
-3 foo
 0
Author: stroz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-01 17:04:02

Prosty sposób:

n = int(input())
arr = list(map(int, input().split()))

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))
 0
Author: rashedcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-26 07:40:34

Wyrazisty sposób na osiągnięcie reverse(enumerate(collection)) w Pythonie 3:

zip(reversed(range(len(collection))), reversed(collection))

W Pythonie 2:

izip(reversed(xrange(len(collection))), reversed(collection))

Nie jestem pewien, dlaczego nie mamy skrótu na to, np.:

def reversed_enumerate(collection):
    return zip(reversed(range(len(collection))), reversed(collection))

Albo dlaczego nie mamy reversed_range()

 0
Author: Barnabas Szabolcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-14 14:58:32
input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
    print(input_list[i])

Myślę, że ten jest również prosty sposób, aby to zrobić... czyta się od końca i maleje aż do długości listy, ponieważ nigdy nie wykonujemy indeksu "end", dlatego dodajemy również -1

 0
Author: Varun Maurya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-22 07:09:28

Jeśli potrzebujesz indeksu, najprostszym sposobem jest odjęcie indeksu zwróconego przez enumerate(reversed()) od len()-1. enumerate() nie wymaga argumentu step.

Jeśli potrzebujesz zrobić to wiele razy, powinieneś użyć generatora:

a = ['b', 'd', 'c', 'a']

def enumerate_reversed(lyst):
    for index, value in enumerate(reversed(lyst)):
        index = len(lyst)-1 - index
        yield index, value

for index, value in enumerate_reversed(a):
    do_something(index, value)

Lub jeśli musisz zrobić to tylko raz:

for index, value in enumerate(reversed(a)):
    index = len(a)-1 - index

    do_something(index, value)
 0
Author: boris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 01:44:54

Zakładając, że zadaniem jest znalezienie ostatniego elementu spełniającego jakiś warunek na liście (tj. pierwszego patrząc wstecz), otrzymuję następujące liczby:

>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.6937971115112305
>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.809093952178955
>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
4.931743860244751
>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n    if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
5.548468112945557
>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n    if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))
6.286104917526245
>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n    i -= 1\n    if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
8.384078979492188
Więc najbrzydsza opcja xrange(len(xs)-1,-1,-1) jest najszybsza.
 0
Author: wonder.mice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-12 17:56:45

Możesz również użyć funkcji "range" lub "count". Jak następuje:

a = ["foo", "bar", "baz"]
for i in range(len(a), 0, -1):
    print(i, a[i-1])

3 baz
2 bar
1 foo

Możesz również użyć "count" z itertools w następujący sposób:

a = ["foo", "bar", "baz"]
from itertools import count, takewhile

def larger_than_0(x):
    return x > 0

for x in takewhile(larger_than_0, count(3, -1)):
    print(x, a[x-1])

3 baz
2 bar
1 foo
 -1
Author: disooqi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-30 11:57:32