简体   繁体   English

从python中的索引0向后切片列表

[英]Slice list backwards from index 0 in python

Let's say I have the following list:假设我有以下列表:

the_list = ['one','two','three','four','five']

How can I slice this python list so that my output is the following (print order does not matter):如何切片此 python 列表,以便我的输出如下(打印顺序无关紧要):

'one','five','four'

I essentially want to start at index 0 and then slice backwards我基本上想从索引 0 开始,然后向后切片

Thanks!谢谢!

Try this:尝试这个:

the_list[0:1] + the_list[-1:2:-1]

This adds 2 list, where your second list starts from the last element, takes the step size of 2 and in reverse.这将添加 2 个列表,其中您的第二个列表从最后一个元素开始,步长为 2,反之亦然。 You can't do multiple slicing but you can select what items to add on or be appended.您不能进行多次切片,但可以选择要添加或附加的项目。

您可以将第一个元素附加到列表的末尾,然后向后切片,不包括第一个元素:

the_list.append(the_list[0]) [the_list[-i] for i in range(1,len(the_list))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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