How to get last items of a list in Python?

后端 未结 5 1445
Happy的楠姐
Happy的楠姐 2020-11-28 02:16

I need the last 9 numbers of a list and I\'m sure there is a way to do it with slicing, but I can\'t seem to get it. I can get the first 9 like this:

num_li         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 02:44

    You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

    >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    >>> a
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    >>> a[-9:]
    [4, 5, 6, 7, 8, 9, 10, 11, 12]
    

    the important line is a[-9:]

提交回复
热议问题