How can I reverse a list in Python?

后端 未结 30 2421
既然无缘
既然无缘 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:31

    You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.

    >>> l = [1,2,3,4,5,6]; nl=[]
    >>> while l:
            nl.append(l.pop())  
    >>> print nl
    [6, 5, 4, 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-21 23:32

    There are 3 methods to get the reversed list:

    1. Slicing Method 1: reversed_array = array[-1::-1]

    2. Slicing Method 2: reversed_array2 = array[::-1]

    3. Using the builtin function: reversed_array = array.reverse()

    The third function actually reversed the list object in place. That means no copy of pristine data is maintained. This is a good approach if you don't want to maintain the old version. But doesn't seem to be a solution if you do want the pristine and reversed version.

    0 讨论(0)
  • 2020-11-21 23:33
    def reverse(text):
        output = []
        for i in range(len(text)-1, -1, -1):
            output.append(text[i])
        return output
    
    0 讨论(0)
  • 2020-11-21 23:34
    array=[0,10,20,40]
    for e in reversed(array):
      print e
    
    0 讨论(0)
  • 2020-11-21 23:34

    Use list comprehension:

    [array[n] for n in range(len(array)-1, -1, -1)]
    
    0 讨论(0)
  • 2020-11-21 23:36

    Using reversed(array) would be the likely best route.

    >>> array = [1,2,3,4]
    >>> for item in reversed(array):
    >>>     print item
    

    Should you need to understand how could implement this without using the built in reversed.

    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
    

    This should take O(N) time.

    0 讨论(0)
提交回复
热议问题