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

42

我试图将两个列表的内容合并,以便稍后对整个数据集进行处理。我最初看了一下内置的insert函数,但它是将一个列表作为整体插入进去,而不是将列表的内容插入。

我可以使用切片和追加来实现列表合并,但是是否有比这更简洁/更符合Python风格的方法呢?

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

array = array[:1] + addition + array[1:]
4个回答

85

你可以在赋值语句的左侧使用切片语法来执行以下操作:

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

那就是最符合 Python 风格的代码了!


36

extend 方法可用于实现此功能,但是在原始列表的末尾进行操作。

addition.extend(array)

6
尽管 David 的解决方案是原帖作者想要的,但你的方案是我一直需要的。非常感谢。 - john_science
我认为应该将加法放在 .extend() 和它之前的数组内。 - tavalendo

3

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']

1

利用列表的星号操作符/列表解包,您可以使用以下方法

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: 其他解包概述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接