How can I reverse a list in Python?

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

    With reversed and list:

    >>> list1 = [1,2,3]
    >>> reversed_list = list(reversed(list1))
    >>> reversed_list
    >>> [3, 2, 1]
    
    0 讨论(0)
  • 2020-11-21 23:21

    Strictly speaking, the question is not how to return a list in reverse but rather how to reverse a list with an example list name array.

    To reverse a list named "array" use array.reverse().

    The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using array = array[::-1].

    0 讨论(0)
  • 2020-11-21 23:22

    Reversing in-place by switching references of opposite indices:

    >>> l = [1,2,3,4,5,6,7]    
    >>> for i in range(len(l)//2):
    ...     l[i], l[-1-i] = l[-1-i], l[i]
    ...
    >>> l
    [7, 6, 5, 4, 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-21 23:25

    For reversing the same list use:

    array.reverse()
    

    To assign reversed list into some other list use:

    newArray = array[::-1] 
    
    0 讨论(0)
  • 2020-11-21 23:25

    You can also use the bitwise complement of the array index to step through the array in reverse:

    >>> array = [0, 10, 20, 40]
    >>> [array[~i] for i, _ in enumerate(array)]
    [40, 20, 10, 0]
    

    Whatever you do, don't do it this way ;)

    0 讨论(0)
  • 2020-11-21 23:25
    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 
    
    0 讨论(0)
提交回复
热议问题