How to get last items of a list in Python?

后端 未结 5 1449
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:37

    Slicing

    Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.

    Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:

    num_list[-9:]
    

    When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")

    Explanation:

    The full notation is

    sequence[start:stop:step]
    

    But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is

    list_copy = sequence[:]
    

    And clearing them is with:

    del my_list[:]
    

    (Lists get list.copy and list.clear in Python 3.)

    Give your slices a descriptive name!

    You may find it useful to separate forming the slice from passing it to the list.__getitem__ method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.

    However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:

    last_nine_slice = slice(-9, None)
    

    The second argument, None, is required, so that the first argument is interpreted as the start argument otherwise it would be the stop argument.

    You can then pass the slice object to your sequence:

    >>> list(range(100))[last_nine_slice]
    [91, 92, 93, 94, 95, 96, 97, 98, 99]
    

    islice

    islice from the itertools module is another possibly performant way to get this. islice doesn't take negative arguments, so ideally your iterable has a __reversed__ special method - which list does have - so you must first pass your list (or iterable with __reversed__) to reversed.

    >>> from itertools import islice
    >>> islice(reversed(range(100)), 0, 9)
    
    

    islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list):

    >>> list(islice(reversed(range(100)), 0, 9))
    [99, 98, 97, 96, 95, 94, 93, 92, 91]
    

提交回复
热议问题