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


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


当前回答

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

其他回答

list_data = [1,2,3,4,5]
l = len(list_data)
i=l+1
rev_data = []
while l>0:
  j=i-l
  l-=1
  rev_data.append(list_data[-j])
print "After Rev:- %s" %rev_data 

这个类使用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]

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

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

另一种方法使用列表理解和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]