从Python中的给定列表中获取最后N个元素
给定一个Python列表,我们只想查找ee的最后几个元素。
带切片
给出了要提取的位置数。基于此,我们设计了一种切片技术,即使用负号从列表末尾切片元素。
示例
listA = ['Mon','Tue','Wed','Thu','Fri','Sat']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using list slicing
res = listA[-n:]
# print result
print("The last 4 elements of the list are : \n",res)输出结果
运行上面的代码给我们以下结果-
Given list : ['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']
# Given list
print("Given list : \n",listA)
# initializing N
n = 4
# using reversed
res = list(islice(reversed(listA), 0, n))
res.reverse()
# print result
print("The last 4 elements of the list are : \n",res)输出结果
运行上面的代码给我们以下结果-
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] The last 4 elements of the list are : ['Wed', 'Thu', 'Fri', 'Sat']
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短