简体   繁体   English

如何在python中进行反向切片?

[英]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

  • the first element is the position of where we want to start ( -1 ); 第一个元素是我们要开始的位置( -1 );
  • the second is where we wish to stop (non-inclusive); 第二个是我们希望停止的地方(非包容性);
  • and the third is the direction (or skip) (backwards). 第三个是方向(或跳过)(向后)。
  • [-2::] will return the last two elements [-2 ::]将返回最后两个元素
  • [::-1] will reverse it [::-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.

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