简体   繁体   中英

How to take N elements from the end of a list in Python? N >= zero

The interval for N includes zero, so a trivial slicing lst[-n:] is not a solution here. I am looking for something like takeright from Scala.

Current solution:

lst = [1, 2, 3]
print(lst[len(lst) - n :])

According to your requirements, you only have to deal with the special case n == 0 .

lst = [1, 2, 3]
print(lst[-n:] if n else [])

is probably the shortest resp. easiest you can have.

If you don't like that, you probably should stick with your solution.

N includes zero, so a trivial slicing lst[-n:] is not a solution here.

If you want to handle the case when n is or less than 0 , then you can use ternary operator in Python. Like this:

result = li[-n:] if n > 0 else []

Or

You can use your solution as mentioned in this answer too! (Thanks to @glglgl)

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