从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']
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短