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条回答
情到深处是孤独
2楼-- · 2018-12-31 09:15

Use list comprehension:

[array[n] for n in range(len(array)-1, -1, -1)]
查看更多
余欢
3楼-- · 2018-12-31 09:15
>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]
查看更多
一个人的天荒地老
4楼-- · 2018-12-31 09:16

ORGANIZING VALUES:

In Python, lists' order too can be manipulated with sort, organizing your variables in numerical/alphabetical order:

Temporarily:

print(sorted(my_list))

Permanent:

my_list.sort(), print(my_list)

You can sort with the flag "reverse=True":

print(sorted(my_list, reverse=True))

or

my_list.sort(reverse=True), print(my_list)

WITHOUT ORGANIZING

Maybe you do not want to sort values, but only reverse the values. Then we can do it like this:

print(list(reversed(my_list)))

**Numbers have priority over alphabet in listing order. The Python values' organization is awesome.

查看更多
梦寄多情
5楼-- · 2018-12-31 09:17
array=[0,10,20,40]
for e in reversed(array):
  print e
查看更多
栀子花@的思念
6楼-- · 2018-12-31 09:17

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]
查看更多
余生无你
7楼-- · 2018-12-31 09:18
>>> L = [0,10,20,40]
>>> L[::-1]
[40, 20, 10, 0]

Extended slice syntax is explained well in the Python What's new Entry for release 2.3.5

By special request in a comment this is the most current slice documentation.

查看更多
登录 后发表回答