How can I reverse a list in Python?

后端 未结 30 2581
既然无缘
既然无缘 2020-11-21 22:32

How can I do the following in Python?

array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of a

30条回答
  •  醉话见心
    2020-11-21 23:25

    This class uses Python magic methods and iterators for reversing, and reverses a list:

    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)  
    

    Output

    [40, 20, 10, 0]
    

提交回复
热议问题