在 Python 中从给定列表中获取最后 N 个元素
pythonserver side programmingprogramming更新于 2026/1/23 2:20:17
给定一个 Python 列表,我们只想找出最后几个元素。
使用切片
给定要提取的位置数。基于此我们设计了切片技术,使用负号从列表末尾切片元素。
示例
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# 给定列表
print("给定列表:\n",listA)
# 初始化 N
n = 4
# 使用列表切片
res = listA[-n:]
# 打印结果
print("列表的最后 4 个元素是:\n",res)
输出
运行上述代码得到以下结果 −
给定列表: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] The last 4 elements of the list are : ['Wed', 'Thu', 'Fri', 'Sat']
使用 isslice
islice 函数将位置数作为参数,同时反转列表的顺序。
示例
from itertools import islice
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# 给定列表
print(" 给定列表:\n",listA)
# 初始化 N
n = 4
# 使用反转
res = list(islice(reversed(listA), 0, n))
res.reverse()
# 打印结果
print("The last 4 elements of the list are : \n",res)
输出
运行上述代码得到以下结果 −
给定列表: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] The last 4 elements of the list are : ['Wed', 'Thu', 'Fri', 'Sat']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

