How can I reverse a list in Python?

后端 未结 30 2566
既然无缘
既然无缘 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]
    
    0 讨论(0)
  • 2020-11-21 23:27
    >>> L = [0,10,20,40]
    >>> L.reverse()
    >>> L
    [40, 20, 10, 0]
    

    Or

    >>> L[::-1]
    [40, 20, 10, 0]
    
    0 讨论(0)
  • 2020-11-21 23:27

    I find (contrary to some other suggestions) that l.reverse() is by far the fastest way to reverse a long list in Python 3 and 2. I'd be interested to know if others can replicate these timings.

    l[::-1] is probably slower because it copies the list prior to reversing it. Adding the list() call around the iterator made by reversed(l) must add some overhead. Of course if you want a copy of the list or an iterator then use those respective methods, but if you want to just reverse the list then l.reverse() seems to be the fastest way.

    Functions

    def rev_list1(l):
        return l[::-1]
    
    def rev_list2(l):
        return list(reversed(l))
    
    def rev_list3(l):
        l.reverse()
        return l
    

    List

    l = list(range(1000000))
    

    Python 3.5 timings

    timeit(lambda: rev_list1(l), number=1000)
    # 6.48
    timeit(lambda: rev_list2(l), number=1000)
    # 7.13
    timeit(lambda: rev_list3(l), number=1000)
    # 0.44
    

    Python 2.7 timings

    timeit(lambda: rev_list1(l), number=1000)
    # 6.76
    timeit(lambda: rev_list2(l), number=1000)
    # 9.18
    timeit(lambda: rev_list3(l), number=1000)
    # 0.46
    
    0 讨论(0)
  • 2020-11-21 23:29
    for x in array[::-1]:
        do stuff
    
    0 讨论(0)
  • 2020-11-21 23:29

    With minimum amount of built-in functions, assuming it's interview settings

    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)
    
    0 讨论(0)
  • 2020-11-21 23:31

    If you want to store the elements of reversed list in some other variable, then you can use revArray = array[::-1] or revArray = list(reversed(array)).

    But the first variant is slightly faster:

    z = range(1000000)
    startTimeTic = time.time()
    y = z[::-1]
    print("Time: %s s" % (time.time() - startTimeTic))
    
    f = range(1000000)
    startTimeTic = time.time()
    g = list(reversed(f))
    print("Time: %s s" % (time.time() - startTimeTic))
    

    Output:

    Time: 0.00489711761475 s
    Time: 0.00609302520752 s
    
    0 讨论(0)
提交回复
热议问题