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


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


当前回答

The cute Solution


class List_reverse():
    def reverse_list(self):
        list = [1, 2, 3, 4, 5, 6]
        list1 = []
        for i in range(1, len(list)+1):
            list1.append(list[-i])
        print(list1)


if __name__ == "__main__":
    obj = List_reverse()
    obj.reverse_list()
    enter code here

其他回答

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

>>> 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.reverse()

将反向列表赋值到其他列表使用:

newArray = array[::-1] 
>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]

使用列表推导式:

[array[n] for n in range(len(array)-1, -1, -1)]

使用一些逻辑

用一些老派的逻辑来练习面试。

从前到后交换数字。使用两个指针索引[0]和索引[last]

def reverse(array):
    n = array
    first = 0
    last = len(array) - 1
    while first < last:
      holder = n[first]
      n[first] = n[last]
      n[last] = holder
      first += 1
      last -= 1
    return n

input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 5, 4, 3, 2, 1, -1]