简体   繁体   中英

How can one reverse the order of a list in Python without using a loop?

How can one reverse the order of a list in Python without using a loop? There are no other constraints on the solution space.

a = ['a','b','c']

you can try

b = a[::-1]

It will reverse the list without using loop.

You can use the same trick on any sequence/container/iterable to get item reversed.

list.reverse()

Whether or not the underlying implementation uses a loop I don't know.

Datastructures - Python Documentation

This reverse function is inefficient because of the way Python handles lists. However, it's worth understanding because it shows how to use a recursive function to replace a loop in a way that can be adapted to almost any language. (In other words, it doesn't depend on built-in features of Python.) Note that l[:1] returns a single-item list containing the first item of l and l[1:] returns all the remaining items in l .

>>> def reverse(l):
...     return reverse(l[1:]) + l[:1] if l else l
... 
>>> reverse([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]

您也可以使用内置函数reversed

a = list(reversed(your_list))

Assuming you want the change in-place:

>>> a = [1,2,3]
>>> a.reverse()
>>> a
[3, 2, 1]
>>> a[:] = a[::-1]
>>> a
[1, 2, 3]

There are many ways:

You can use extended List Slicing :

>>> print [1, 2, 3, 4, 5][::-1]
[5, 4, 3, 2, 1]

Or use the built in .reverse() function:

>>> L = [1, 2, 3, 4, 5]
>>> L.reverse()
>>> print L
[5, 4, 3, 2, 1]

Or use reversed() , which returns the reversed list - but as an iterator:

>>> L = [1, 2, 3, 4, 5]
>>> print reversed(L)
<listreverseiterator object at 0x2c3630>
>>> print list(reversed(L))
[5, 4, 3, 2, 1]

Timing comparisons:

$ python -m timeit "L = range(1000)" "L = L[::-1]"
100000 loops, best of 3: 11.8 usec per loop

$ python -m timeit "L = range(1000)" "L.reverse()"
100000 loops, best of 3: 9.13 usec per loop

$ python -m timeit "L = range(1000)" "L = list(reversed(L))"
100000 loops, best of 3: 19.1 usec per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM