如何在Python中反向迭代列表?


请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?


当前回答

可以使用__reverse__来完成,它会返回一个生成器。

>>> l = [1,2,3,4,5]
>>> for i in l.__reversed__():
...   print i
... 
5
4
3
2
1
>>>

其他回答

这个类使用Python魔法方法和迭代器进行反转,并反转列表:

class Reverse(object):
    """ Builds a reverse method using magic methods """

    def __init__(self, data):
        self.data = data
        self.index = len(data)


    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration

        self.index = self.index - 1
        return self.data[self.index]


REV_INSTANCE = Reverse([0, 10, 20, 40])

iter(REV_INSTANCE)

rev_list = []
for i in REV_INSTANCE:
    rev_list.append(i)

print(rev_list)  

输出

[40, 20, 10, 0]
for x in array[::-1]:
    do stuff

使用切片,例如array = array[::-1],是一个简洁的技巧,非常python化,但对于新手来说可能有点晦涩。使用reverse()方法是进行日常编码的好方法,因为它易于阅读。

然而,如果你需要在面试问题中反转列表,你可能无法使用这些内置的方法。面试官会看你如何解决问题,而不是Python知识的深度,需要一个算法的方法。下面的例子,使用一个经典的交换,可能是一种方法:-

def reverse_in_place(lst):      # Declare a function
    size = len(lst)             # Get the length of the sequence
    hiindex = size - 1
    its = size/2                # Number of iterations required
    for i in xrange(0, its):    # i is the low index pointer
        temp = lst[hiindex]     # Perform a classic swap
        lst[hiindex] = lst[i]
        lst[i] = temp
        hiindex -= 1            # Decrement the high index pointer
    print "Done!"

# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]

print array                    # Print the original sequence
reverse_in_place(array)        # Call the function passing the list
print array                    # Print reversed list


**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]

注意,这将不适用于元组或字符串序列,因为字符串和元组是不可变的,也就是说,您不能写入它们来更改元素。

要获得一个新的反向列表,应用reversed函数并将项目收集到一个列表中:

>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]

在列表中向后迭代:

>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
...     print(x)
40
20
10
0

使用列表。Reverse将列表就地反转:

>>> xs = [0, 10, 20, 40]
>>> xs.reverse()
>>> xs
[40, 20, 10, 0]

使用切片以相反的顺序创建一个新列表:

>>> xs[::-1]
[40, 20, 10, 0]