python中取列表的后半部分元素

 

 1、for循环

>>> test1 = ["aa","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn"]
>>> type(test1)
<class 'list'>
>>> len(test1)
14
>>> test2 = []
>>> test2
[]
>>> for i in range(-10,0):    ## 取后10个元素
    test2.append(test1[i])

    
>>> test2
['ee', 'ff', 'gg', 'hh', 'ii', 'jj', 'kk', 'll', 'mm', 'nn']

 

 

 2、列表分片

>>> test1 = ["aa","bb","cc","dd","ee","ff","gg"]
>>> type(test1)
<class 'list'>
>>> len(test1)
7
>>> test1[-3:]   ## 后三个元素
['ee', 'ff', 'gg']
>>> test2 = list(range(10))
>>> test2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test2[-5:]   ## 后五个元素
[5, 6, 7, 8, 9]

 

posted @ 2020-12-18 20:14  小鲨鱼2018  阅读(2400)  评论(0编辑  收藏  举报