python - 在 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`
解决方案
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]
是最简单的。
推荐阅读
- ios - AFNetworking setImageWithURLRequest 不起作用
- mysql - 如何多次加入一个表?
- masstransit - 使用 CreateRequestClient 方法时启动 MassTransit 总线的正确方法是什么?
- php - 我如何制作多个负正则表达式?
- omnet++ - 如何在 Veins 上添加更多 RSU 节点
- statistics - 具有重复的不平衡数据的 PCA 结果
- sql - SQL计算组内不同值的总和和数量
- python - 更有效地用特定列中的行的平均值填充 NaN
- python - 破折号 python 加载然后更新
- c - 如何设置矩阵的基地址?