我可以在Python中使用前置元素而不是附加元素来扩展列表吗?
问题描述:
我可以表演
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?
喜欢
a = [1,2,3]
b = [4,5,6]
a.someaction(b)
# a is now [4,5,6,1,2,3]
如果重要的话,我使用2.7.5版本.
I use version 2.7.5, if it is important.
答
您可以分配给切片:
a[:0] = b
演示:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a[:0] = b
>>> a
[4, 5, 6, 1, 2, 3]
本质上,list.extend()
是对list[len(list):]
切片的分配.
Essentially, list.extend()
is an assignment to the list[len(list):]
slice.
您可以在任何位置插入"另一个列表,只需解决该位置的空片即可.
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]