如何将一个列表的内容插入另一个列表中

时间:2011-04-27 14:39:15

标签: list python

我正在尝试组合两个列表的内容,以便稍后对整个数据集执行处理。我最初查看了内置的insert函数,但它作为列表插入,而不是列表的内容。

我可以对列表进行切片和附加,但是有更清洁/更多的Pythonic方式来做我想做的事情:

array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

array = array[:1] + addition + array[1:]

4 个答案:

答案 0 :(得分:68)

您可以使用作业左侧的切片语法执行以下操作:

>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> array[1:1] = ['quick', 'brown']
>>> array
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

这就像Pythonic一样!

答案 1 :(得分:32)

list对象的extend方法执行此操作,但在原始列表的末尾。

addition.extend(array)

答案 2 :(得分:2)

insert(i,j),其中i是索引,j是您要插入的内容,不会添加为列表。相反,它会添加为列表项:

array = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
array.insert(1,'brown')

新阵列将是:

array = ['the', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

答案 3 :(得分:1)

利用 splat operator / list unpacking 作为列表,您可以使用

array    = ['the', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
addition = ['quick', 'brown']

# like this
array2    = ['the', *addition, 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

# or like this
array = [ *array[:1], *addition, *array[1:]]

print(array)
print(array2)

得到

['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

运算符使用 PEP 448: Additional Unpacking Generalizations 进行介绍。

相关问题