Skip to main content
 首页 » 编程设计

python之在列表中的每个项目之后插入一个项目(Python)

2025年05月04日9lexus

假设我有一个这样的列表:

a = [[1, 2, 3], [4, 5, 6]] 
filler = ['cat'] 

我怎么得到

b = [[1 ,2 ,3], ['cat'], [4, 5, 6], ['cat']]  

作为输出?

请您参考如下方法:

我更喜欢将 itertools 用于这样的事情:

>>> import itertools as it 
>>> a = [[1, 2, 3], [4, 5, 6]] 
>>> filler = ['cat'] 
>>> list(it.chain.from_iterable(it.izip(a, it.repeat(filler)))) 
[[1, 2, 3], ['cat'], [4, 5, 6], ['cat']]