简体   繁体   中英

First element and last ones of list, Python

I know there are similar questions to this one asking for only the first element and the last one, but I think this question is different:

Given a list a=[1,2,3,4,5,6,7,8,9,10] , is it possible to write in an elegant form a way to get the first element and the last three (or n) ones in one line in a way such that it returns [8,9,10,1] ?

I attempted using a[7:-1] , but since it understands as if they were inverted indices, it doesn't work.

I also know it's possible just to do a[len(a)-n:]+[a[0]] , but I want to know if there is a 'brackets' way.

No, there isn't. Concatenating the two slices is the best you can get:

a[-3:] + a[:1]

With some utils, you can at least get this result from a single continuous slice which may simplify some code to calculate the bounding indeces and check for overlaps or staying inbounds:

from itertools import cycle, islice

list(islice(cycle(a), 7, 11))
# [8, 9, 10, 1]

See:

Alternative using itemgetter:

from operator import itemgetter
list(itemgetter(*range(7,10),0)(a))

output:

[8, 9, 10, 1]

you cant do a[len(a)-n:]+a[0]

you will get an error

 TypeError: can only concatenate list (not "int") to list 
                                                                                                                      

because a[len(a)-n:] is a list and a[0] is a int

you can do a[len(a)-n:]+a[0:1]

a=[1,2,3,4,5,6,7,8,9,10]
n=3
print(a[(len(a)-n):]+a[0:1])

output:

[8, 9, 10, 1] 

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