Add entry to beginning of list and remove the last one

后端 未结 5 1995
生来不讨喜
生来不讨喜 2020-12-16 16:40

I have a list of about 40 entries. And I frequently want to append an item to the start of the list (with id 0) and want to delete the last entry (

相关标签:
5条回答
  • 2020-12-16 16:53

    Use collections.deque:

    >>> import collections
    >>> q = collections.deque(["herp", "derp", "blah", "what", "da.."])
    >>> q.appendleft('wuggah')
    >>> q.pop()
    'da..'
    >>> q
    deque(['wuggah', 'herp', 'derp', 'blah', 'what'])
    
    0 讨论(0)
  • 2020-12-16 16:55

    Use insert() to place an item at the beginning of the list:

    myList.insert(0, "wuggah")
    

    Use pop() to remove and return an item in the list. Pop with no arguments pops the last item in the list

    myList.pop() #removes and returns "da..."
    
    0 讨论(0)
  • 2020-12-16 16:57

    Another approach

    L = ["herp", "derp", "blah", "what", "da..."]
    
    L[:0]= ["wuggah"]
    L.pop()             
    
    0 讨论(0)
  • 2020-12-16 17:06

    Here's a one-liner, but it probably isn't as efficient as some of the others ...

    myList=["wuggah"] + myList[:-1]
    

    Also note that it creates a new list, which may not be what you want ...

    0 讨论(0)
  • 2020-12-16 17:11

    Use collections.deque

    In [21]: from collections import deque
    
    In [22]: d = deque([], 3)   
    
    In [24]: for c in '12345678':
       ....:     d.appendleft(c)
       ....:     print d
       ....:
    deque(['1'], maxlen=3)
    deque(['2', '1'], maxlen=3)
    deque(['3', '2', '1'], maxlen=3)
    deque(['4', '3', '2'], maxlen=3)
    deque(['5', '4', '3'], maxlen=3)
    deque(['6', '5', '4'], maxlen=3)
    deque(['7', '6', '5'], maxlen=3)
    deque(['8', '7', '6'], maxlen=3)
    
    0 讨论(0)
提交回复
热议问题