简体   繁体   中英

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):

'one','five','four'

I essentially want to start at index 0 and then slice backwards

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. 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))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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