[英]How to do reverse slicing in python?
Say I have lst = [1, 2, 3]
and I want to access the last two elements in reverse order, as in [3, 2]
假设我有lst = [1, 2, 3]
并且我想以相反的顺序访问最后两个元素,如[3, 2]
How do I do that using slicing? 我该如何使用切片?
Simply put bounds into your slice: 只需将边界放入切片中:
>>> [1,2,3][-1:-3:-1]
[3, 2]
In the slice -1:-3:-1
: 在切片-1:-3:-1
:
-1
); 第一个元素是我们要开始的位置( -1
); So the answer will be: 因此答案将是:
lst[-2::][::-1]
I checked @donkopotamus's answer and it is actually the best answer 我检查了@donkopotamus的答案,它实际上是最好的答案
Get the last two elements! 获取最后两个元素!
And then reverse it! 然后扭转它!
>>> lst
[1, 2, 3]
>>> lst[-2:][::-1]
[3, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.