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


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


当前回答

def reverse(text):
    output = []
    for i in range(len(text)-1, -1, -1):
        output.append(text[i])
    return output

其他回答

内置功能最少,假设是面试设置

array = [1, 2, 3, 4, 5, 6,7, 8]
inverse = [] #create container for inverse array
length = len(array)  #to iterate later, returns 8 
counter = length - 1  #because the 8th element is on position 7 (as python starts from 0)

for i in range(length): 
   inverse.append(array[counter])
   counter -= 1
print(inverse)

下面是一种使用生成器对反向进行惰性计算的方法:

def reverse(seq):
    for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
        yield seq[x] #Yield a value to the generator

现在像这样迭代:

for x in reverse([1, 2, 3]):
    print(x)

如果你需要一个列表:

l = list(reverse([1, 2, 3]))

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

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

我在一次面试的python代码测试中遇到了这个问题。 以下是我的答案。 注意它适用于任何值任何长度

def get_reverse(list_check, count_num):
    final_list =[]
    for index in range(list_length):
        value = list_check[count_num]
        final_list.append(value)
        count_num = count_num -1

    return final_list

new_list = ['A', 'GOAT', 'C', 'D', 'Mac']

list_length = len(new_list)
x = list_length -1

print(get_reverse(new_list, x))