将条目添加到列表的开头并删除最后一个 [英] Add entry to beginning of list and remove the last one

查看:24
本文介绍了将条目添加到列表的开头并删除最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我该如何做到最好?

包含 5 个条目的示例:

[0] = "herp"[1] = "derp"[2] = "废话"[3] = "什么"[4] = "大..."

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

[0] = "wuggah"[1] = "疱疹"[2] = "derp"[3] = "废话"[4] = "什么"

而且我不想最终手动将所有条目一个接一个地移动到下一个 ID.

解决方案

使用 collections.deque:

<预><代码>>>>进口藏品>>>q = collections.deque(["herp", "derp", "blah", "what", "da.."])>>>q.appendleft('wuggah')>>>q.pop()'哒..'>>>qdeque(['wuggah', 'herp', 'derp', 'blah', 'what'])

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 (with id 40) of the list.

How do I do this the best?

Example with 5 entries:

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

after adding "wuggah" and deleting last it should be like:

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

And I don't want to end up manually moving them one after another all of the entries to the next id.

解决方案

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

这篇关于将条目添加到列表的开头并删除最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆