如何在 Python 中反转列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3940128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:26:33  来源:igfitidea点击:

How can I reverse a list in Python?

pythonlist

提问by Leo.peis

How can I do the following in Python?

如何在 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.

我需要有一个数组的元素,但是从头到尾。

采纳答案by codaddict

You can make use of the reversedfunction for this as:

您可以reversed为此使用该功能:

>>> array=[0,10,20,40]
>>> for i in reversed(array):
...     print(i)

Note that reversed(...)does not return a list. You can get a reversed list using list(reversed(array)).

请注意,reversed(...)不会返回列表。您可以使用list(reversed(array)).

回答by mechanical_meat

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

扩展切片语法在 Python What's new Entry for release 中有很好的解释2.3.5

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

根据评论中的特殊要求,这是最新的切片文档

回答by Swiss

for x in array[::-1]:
    do stuff

回答by ghostdog74

>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

Or

或者

>>> L[::-1]
[40, 20, 10, 0]

回答by nonopolarity

array=[0,10,20,40]
for e in reversed(array):
  print e

回答by John Machin

The most direct translation of your requirement into Python is this forstatement:

将您的需求最直接地翻译成 Python 是以下for语句:

for i in xrange(len(array) - 1, -1, -1):
   print i, array[i]

This is rather cryptic but may be useful.

这相当神秘,但可能有用。

回答by Pawan Kumar

For reversing the same list use:

要反转相同的列表,请使用:

array.reverse()

To assign reversed list into some other list use:

要将反向列表分配到其他列表中,请使用:

newArray = array[::-1] 

回答by robertmoggach

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.

严格来说,问题不是如何反向返回列表,而是如何使用示例列表名称反向返回列表array

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

反转名为"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].

所描述的非常有用的 slice 方法也可用于通过使用array = array[::-1].

回答by fahad

This is to duplicate the list:

这是复制列表:

L = [0,10,20,40]
p = L[::-1]  #  Here p will be having reversed list

This is to reverse the list in-place:

这是就地反转列表:

L.reverse() # Here L will be reversed in-place (no new list made)

回答by koo

Use list comprehension:

使用列表理解:

[array[n] for n in range(len(array)-1, -1, -1)]