📌  相关文章
📜  Python|从给定列表中获取最后 N 个元素

📅  最后修改于: 2022-05-13 01:55:09.419000             🧑  作者: Mango

Python|从给定列表中获取最后 N 个元素

访问列表中的元素有许多类型和变体。这些是Python编程的重要组成部分,必须具备执行相同操作的知识。本文讨论了获取列表最后 N 个元素的方法。让我们讨论执行此任务的某些解决方案。
方法#1:使用列表切片
这个问题可以在 1 行中执行,而不是使用Python提供的列表切片功能使用循环。减号运算符指定要从后端进行切片。

Python3
# Python3 code to demonstrate
# Get last N elements from list
# using list slicing
 
# initializing list
test_list = [4, 5, 2, 6, 7, 8, 10]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing N
N = 5
 
# using list slicing
# Get last N elements from list
res = test_list[-N:]
 
# print result
print("The last N elements of list are : " + str(res))


Python3
# Python3 code to demonstrate
# Get last N elements from list
# using islice() + reversed()
from itertools import islice
 
# initializing list
test_list = [4, 5, 2, 6, 7, 8, 10]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing N
N = 5
 
# using islice() + reversed()
# Get last N elements from list
res = list(islice(reversed(test_list), 0, N))
res.reverse()
 
# print result
print("The last N elements of list are : " + str(res))


输出 :
The original list : [4, 5, 2, 6, 7, 8, 10]
The last N elements of list are : [2, 6, 7, 8, 10]


方法#2:使用 islice() + reversed()
内置函数也可用于执行此特定任务。 islice函数可用于获取切片列表, reversed函数用于从后端获取元素。

Python3

# Python3 code to demonstrate
# Get last N elements from list
# using islice() + reversed()
from itertools import islice
 
# initializing list
test_list = [4, 5, 2, 6, 7, 8, 10]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing N
N = 5
 
# using islice() + reversed()
# Get last N elements from list
res = list(islice(reversed(test_list), 0, N))
res.reverse()
 
# print result
print("The last N elements of list are : " + str(res))
输出 :
The original list : [4, 5, 2, 6, 7, 8, 10]
The last N elements of list are : [2, 6, 7, 8, 10]