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

43 投票
4 回答
30604 浏览
提问于 2025-04-16 16:31

我想把两个列表的内容合并在一起,这样我就可以对整个数据集进行处理。一开始我查看了内置的 insert 函数,但发现它是把一个列表作为整体插入,而不是把列表里的内容逐个插入。

我可以通过切片和添加的方式来合并列表,但有没有比这样做更简洁、更符合Python风格的方法呢?

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

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

4 个回答

3

insert(i,j)这个函数,其中i是位置索引,j是你想要插入的内容,并不是把j当作一个整体的列表来添加。相反,它会把j当作一个列表中的一个项目来添加:

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

新的数组会变成:

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

列表对象的 extend 方法可以做到这一点,不过它是在原始列表的末尾添加内容。

addition.extend(array)
87

你可以在赋值的左边使用切片语法来做到以下这些:

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

这就是最符合Python风格的写法了!

撰写回答