我可以使用 prepend 元素而不是 append 来扩展 Python 中的列表吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19736058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I extend list in Python with prepend elements instead of append?
提问by Daniil Grankin
I can perform
我可以表演
a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]
Is there way to perform an action for extending list and adding new items to the beginning of the list?
有没有办法执行扩展列表并将新项目添加到列表开头的操作?
Like this
像这样
a = [1,2,3]
b = [4,5,6]
a.someaction(b)
# a is now [4,5,6,1,2,3]
I use version 2.7.5, if it is important.
如果重要的话,我使用 2.7.5 版。
采纳答案by Martijn Pieters
You can assign to a slice:
您可以分配给一个切片:
a[:0] = b
Demo:
演示:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[:0] = b
>>> a
[4, 5, 6, 1, 2, 3]
Essentially, list.extend()
is an assignment to the list[len(list):]
slice.
本质上,list.extend()
是对list[len(list):]
切片的赋值。
You can 'insert' another list at any position, just address the empty slice at that location:
您可以在任何位置“插入”另一个列表,只需在该位置处理空切片:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[1:1] = b
>>> a
[1, 4, 5, 6, 2, 3]
回答by Artur
This is what you need ;-)
这就是你需要的 ;-)
a = b + a
回答by TerryA
You could use collections.deque
:
你可以使用collections.deque
:
import collections
a = collections.deque([1, 2, 3])
b = [4, 5, 6]
a.extendleft(b[::-1])
回答by dstromberg
If you need fast operations andyou need to be able to access arbitrary elements, try a treap or red-black tree.
如果您需要快速操作并且需要能够访问任意元素,请尝试使用 treap 或红黑树。
>>> import treap as treap_mod
>>> treap = treap_mod.treap()
>>> for i in range(100000):
... treap[i] = i
...
>>> treap[treap.find_min() - 1] = -1
>>> treap[100]
100
Most operations on treaps and red-black trees can be done in O(log(n)). Treaps are purportedly faster on average, but red-black trees give a lower variance in operation times.
大多数对树和红黑树的操作都可以在 O(log(n)) 中完成。据称 Treap 平均速度更快,但红黑树的操作时间差异较小。