How can I reverse a list in Python?

2018-12-31 08:58发布

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 an array, but from the end to the beginning.

标签: python list
30条回答
泛滥B
2楼-- · 2018-12-31 09:03

You can use reversed()

array=[0,10,20,40]

for e in reversed(array):
  print e
查看更多
素衣白纱
3楼-- · 2018-12-31 09:04

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

查看更多
不再属于我。
4楼-- · 2018-12-31 09:06
def reverse(text):
    lst=[]
    for i in range(0,len(text)):
        lst.append(text[(len(text)-1)-i])
    return ''.join(lst)

print reverse('reversed')
查看更多
只靠听说
5楼-- · 2018-12-31 09:08

For reversing the same list use:

array.reverse()

To assign reversed list into some other list use:

newArray = array[::-1] 
查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 09:08

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.

查看更多
公子世无双
7楼-- · 2018-12-31 09:12
>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

Or

>>> L[::-1]
[40, 20, 10, 0]
查看更多
登录 后发表回答