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


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


当前回答

另一种方法使用列表理解和abs

array = [0, 10, 20, 40]

reversed_array = [array[abs(indx)] for indx in range(abs(len(array)-1),1)]
            
reversed_array
[40, 20, 10, 0]

其他回答

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

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

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

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

使用反向(数组)可能是最好的方法。

>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>>     print item

如果你需要了解如何实现这个不使用内置反转。

def reverse(a):
    midpoint = len(a)/2
    for item in a[:midpoint]:
        otherside = (len(a) - a.index(item)) - 1
        temp = a[otherside]
        a[otherside] = a[a.index(item)]
        a[a.index(item)] = temp
    return a

这需要O(N)时间。

array=[0,10,20,40]
for e in reversed(array):
  print e
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 1]

使用切片,例如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]

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