首页 > 解决方案 > 在 Python 中反转列表/数组

问题描述

这四种反转列表的方法有什么区别?哪个更快?

1.

list.reverse()

2.

list(reversed(list))

3.

list[::-1]

4.

while(start < end):
    list[start], list[end] = list[end], list[start]
    start += 1
    end -= 1`

标签: pythonlistalgorithmsortingreverse

解决方案


I'll rename the list variable to xs to avoid confusion with the function list.

xs.reverse() mutates the original list, so that the values to the reference xs changes everywhere.

reversed(xs) creates an iterator, so calling list on it makes a new list with the values reversed. No mutations happen here.

xs[::-1] creates a new list reversed. This has the same effect as list(reversed(xs)). Not sure about which one is more performant though.

The procedure you wrote is also mutating, so that the original list xs changes.

如果性能不是问题,我会推荐非变异版本,因为它会导致令人惊讶的行为。在这种情况下xs[::-1]是最简单的。


推荐阅读