问题:在Python中以相反顺序遍历列表

所以我可以从开始到len(collection)结束collection[0]

我还希望能够访问循环索引。

So I can start from len(collection) and end in collection[0].

I also want to be able to access the loop index.


回答 0

使用内置reversed()功能:

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

要同时访问原始索引,请在列表上使用,然后将其传递给reversed()

>>> for i, e in reversed(list(enumerate(a))):
...     print(i, e)
... 
2 baz
1 bar
0 foo

由于enumerate()返回生成器并且生成器不能反转,因此需要将其转换为list第一个。

Use the built-in reversed() function:

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

To also access the original index, use on your list before passing it to reversed():

>>> for i, e in reversed(list(enumerate(a))):
...     print(i, e)
... 
2 baz
1 bar
0 foo

Since enumerate() returns a generator and generators can’t be reversed, you need to convert it to a list first.


回答 1

你可以做:

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

(或者您想要在for循环中执行的任何操作。)

[::-1]切片反转for循环在列表中(但不会实际修改列表的“永久”)。

You can do:

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

(Or whatever you want to do in the for loop.)

The [::-1] slice reverses the list in the for loop (but won’t actually modify your list “permanently”).


回答 2

如果您需要循环索引,并且不想遍历整个列表两次,或者不想使用额外的内存,则可以编写一个生成器。

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

If you need the loop index, and don’t want to traverse the entire list twice, or use extra memory, I’d write a 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

回答 3

可以这样完成:

对于范围(len(collect)-1,-1,-1)中的i:
    印刷品收藏[i]

    #为python 3打印(collection [i])。

因此,您的猜测非常接近:)有点尴尬,但这基本上是在说:从小于1开始len(collection),一直走到-1之前,以-1为步长。

Fyi,该help功能非常有用,因为它使您可以从Python控制台查看文档,例如:

help(range)

It can be done like this:

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

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

So your guess was pretty close :) A little awkward but it’s basically saying: start with 1 less than len(collection), keep going until you get to just before -1, by steps of -1.

Fyi, the help function is very useful as it lets you view the docs for something from the Python console, eg:

help(range)


回答 4

reversed内置功能非常方便:

for item in reversed(sequence):

文档的反向解释它的局限性。

对于必须与索引一起反向遍历序列的情况(例如,对于更改序列长度的就地修改),我需要将此函数定义为我的codeutil模块:

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

这避免了创建序列的副本。显然,这些reversed限制仍然适用。

The reversed builtin function is handy:

for item in reversed(sequence):

The documentation for reversed explains its limitations.

For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modifications changing the sequence length), I have this function defined an my codeutil module:

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

This one avoids creating a copy of the sequence. Obviously, the reversed limitations still apply.


回答 5

无需重新创建新列表,可以通过建立索引来实现:

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

要么

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

How about without recreating a new list, you can do by indexing:

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

OR

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

回答 6

>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

要么

>>> print l[::-1]
['d', 'c', 'b', 'a']
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

OR

>>> print l[::-1]
['d', 'c', 'b', 'a']

回答 7

我喜欢单线生成器方法:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))

I like the one-liner generator approach:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))

回答 8

另外,您可以使用“范围”或“计数”功能。如下:

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

3 baz
2 bar
1 foo

您还可以按以下方式使用itertools中的“ count”:

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

Also, you could use either “range” or “count” functions. As follows:

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

3 baz
2 bar
1 foo

You could also use “count” from itertools as following:

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

回答 9

list.reverse()照常使用,然后进行迭代。

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

Use list.reverse() and then iterate as you normally would.

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


回答 10

没有导入的方法:

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

要么

for i in arr[::-1]:
    print(i)

An approach with no imports:

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

or

for i in arr[::-1]:
    print(i)

回答 11

def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)
def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)

回答 12

对于有什么价值的事情,您也可以这样做。很简单。

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]

for what ever it’s worth you can do it like this too. very simple.

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]

回答 13

reverse(enumerate(collection))在python 3中实现的一种表达方式:

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

在python 2:

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

我不确定为什么我们没有快捷方式,例如:

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

还是为什么我们没有 reversed_range()

An expressive way to achieve reverse(enumerate(collection)) in python 3:

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

in python 2:

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

I’m not sure why we don’t have a shorthand for this, eg.:

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

or why we don’t have reversed_range()


回答 14

如果您需要索引并且列表很小,那么最容易理解的方法是reversed(list(enumerate(your_list)))按照接受的答案进行操作。但这会创建列表的副本,因此,如果列表占用了很大一部分内存,则必须减去enumerate(reversed())从中返回的索引len()-1

如果您只需要执行一次:

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

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

    do_something(index, value)

或者,如果您需要多次执行此操作,则应使用生成器:

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)

If you need the index and your list is small, the most readable way is to do reversed(list(enumerate(your_list))) like the accepted answer says. But this creates a copy of your list, so if your list is taking up a large portion of your memory you’ll have to subtract the index returned by enumerate(reversed()) from len()-1.

If you just need to do it once:

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

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

    do_something(index, value)

or if you need to do this multiple times you should use a generator:

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)

回答 15

反向功能在这里很方便:

myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
    print x

the reverse function comes in handy here:

myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
    print x

回答 16

您还可以使用while循环:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1

You can also use a while loop:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1

回答 17

您可以在普通的for循环中使用负索引:

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

要访问索引,就好像您正在遍历集合的反向副本一样,请使用i - 1

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

要访问原始的非反向索引,请使用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

You can use a negative index in an ordinary for loop:

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

To access the index as though you were iterating forward over a reversed copy of the collection, use i - 1:

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

To access the original, un-reversed index, use 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

回答 18

如果您不介意索引为负,则可以执行以下操作:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

If you don’t mind the index being negative, you can do:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

回答 19

我认为最优雅的方法是转换enumeratereversed使用以下生成器

(-(ri+1), val) for ri, val in enumerate(reversed(foo))

生成enumerate迭代器的逆向

例:

foo = [1,2,3]
bar = [3,6,9]
[
    bar[i] - val
    for i, val in ((-(ri+1), val) for ri, val in enumerate(reversed(foo)))
]

结果:

[6, 4, 2]

I think the most elegant way is to transform enumerate and reversed using the following generator

(-(ri+1), val) for ri, val in enumerate(reversed(foo))

which generates a the reverse of the enumerate iterator

Example:

foo = [1,2,3]
bar = [3,6,9]
[
    bar[i] - val
    for i, val in ((-(ri+1), val) for ri, val in enumerate(reversed(foo)))
]

Result:

[6, 4, 2]

回答 20

其他答案是好的,但是如果您要作为 列表理解样式

collection = ['a','b','c']
[item for item in reversed( collection ) ]

The other answers are good, but if you want to do as List comprehension style

collection = ['a','b','c']
[item for item in reversed( collection ) ]

回答 21

要使用负索引,请执行以下操作:从-1开始,然后在每次迭代后退-1。

>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
...     print i, a[i]
... 
-1 baz
-2 bar
-3 foo

To use negative indices: start at -1 and step back by -1 at each iteration.

>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
...     print i, a[i]
... 
-1 baz
-2 bar
-3 foo

回答 22

一个简单的方法:

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

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

A simple way :

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

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

回答 23

input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
    print(input_list[i])

我认为这也是一种简单的方法…从末尾读取并不断递减直到列表的长度,因为我们从不执行“ end”索引,因此也添加了-1

input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
    print(input_list[i])

i think this one is also simple way to do it… read from end and keep decrementing till the length of list, since we never execute the “end” index hence added -1 also


回答 24

假设任务是在列表中找到满足某些条件的最后一个元素(即向后看时的第一个元素),我得到以下数字:

>>> 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

因此,最丑陋的选择xrange(len(xs)-1,-1,-1)是最快的。

Assuming task is to find last element that satisfies some condition in a list (i.e. first when looking backwards), I’m getting following numbers:

>>> 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

So, the ugliest option xrange(len(xs)-1,-1,-1) is the fastest.


回答 25

您可以使用生成器:

li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))

最后:

for i in gen:
    print(li[i])

希望对您有帮助。

you can use a generator:

li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))

finally:

for i in gen:
    print(li[i])

hope this help you.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。