【问题标题】:Add entry to beginning of list and remove the last one将条目添加到列表的开头并删除最后一个
【发布时间】:2012-04-26 16:39:56
【问题描述】:

我有大约 40 个条目的 list。而且我经常想将一个项目附加到列表的开头(id 为 0),并想删除列表的 last 条目(id 为 40)。

我怎样才能做到最好?

5 个条目的示例:

[0] = "herp"
[1] = "derp"
[2] = "blah"
[3] = "what"
[4] = "da..."

添加"wuggah" 并删除最后应该是这样的:

[0] = "wuggah"
[1] = "herp"
[2] = "derp"
[3] = "blah"
[4] = "what"

而且我不想最终手动将它们一个接一个地移动到下一个 id。

【问题讨论】:

  • “而且我不想最终手动将它们一个接一个地移动所有条目到下一个 id。”在内部,列表对象分配的列表比当前使用的列表的大小更大(10 个元素,但列表实际上比这大得多)。所以在幕后它为你做所有这些 - 这摊销了插入的运行时间,在特定位置弹出和其他操作尽可能低。 wiki.python.org/moin/TimeComplexity

标签: python list append


【解决方案1】:

另一种方法

L = ["herp", "derp", "blah", "what", "da..."]

L[:0]= ["wuggah"]
L.pop()             

【讨论】:

    【解决方案2】:

    使用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)
    

    【讨论】:

    • 在这里使用最大长度是一个更好的解决方案,更优雅,也就是说,OP 想要添加项目,而不是附加它 - 你想要 deque.appendleft()。已编辑。
    【解决方案3】:

    这是一个单行,但它可能不如其他一些高效...

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

    另请注意,它会创建一个新列表,这可能不是您想要的...

    【讨论】:

      【解决方案4】:

      使用insert() 将项目放在列表的开头:

      myList.insert(0, "wuggah")
      

      使用pop() 删除并返回列表中的项目。不带参数的弹出弹出列表中的最后一项

      myList.pop() #removes and returns "da..."
      

      【讨论】:

        【解决方案5】:

        使用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'])
        

        【讨论】:

        • 谢谢。这和myList.insert(0, "wuggah")一样吗?
        • @wagglewax 是的,除了这是一个 O(1) 操作而不是 O(n)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-28
        • 1970-01-01
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-09
        相关资源
        最近更新 更多