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.
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.
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]
这篇关于我可以在 Python 中使用前置元素而不是附加来扩展列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!