All but the last N elements of iterator in Python

前端 未结 6 1538
情书的邮戳
情书的邮戳 2021-01-02 21:10

What is the best way to get all but the last N elements of an iterator in Python? Here is an example of it in theoretical action:

>>> list(all_but_         


        
6条回答
  •  生来不讨喜
    2021-01-02 22:00

    For a list you could do this:

    def all_but_the_last_n(aList, N):
        return aList[:len(aList) - N]
    
    myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    N = 4
    
    print(all_but_the_last_n(myList, N))
    

    Will print:

    [0, 1, 2, 3, 4, 5]
    

提交回复
热议问题