2011-04-27 70 views
21

我想组合两个列表的内容,以便稍后对整个数据集执行处理。我最初看着内置的insert函数,但它插入的是列表,而不是列表的内容。如何将一个列表的内容插入另一个列表

我可以切片和追加的名单,但有没有这样做的一个清洁/更Python的方式我想要的不是这样的:

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

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

回答

55

您可以使用在左侧的切片语法做以下作业:

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

这就像Pythonic一样!

23

列表对象的extend方法做到这一点,但在原始列表的末尾。

addition.extend(array) 
+2

,而David的解决方案是OP想要的东西,你是我需要的所有时间。非常感谢。 – theJollySin 2013-04-12 05:05:02

1

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'] 
相关问题