以Python形式将多个值插入列表

时间:2013-02-23 14:55:33

标签: python list insert idiomatic

我想转此列表:

l=["Three","Four","Five","Six"]

进入这一个:

['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]

我使用此代码(效果很好)来执行此操作:

for i,j in zip(range(1,len(l)*2,2),range(3,7)*2):
    l.insert(i,j)

但我猜Python不会为此感到骄傲。这有更短的方法吗?

2 个答案:

答案 0 :(得分:13)

我可能会这样做:

>>> a = ["Three","Four","Five","Six"]
>>> b = range(3,7)
>>> zip(a,b)
[('Three', 3), ('Four', 4), ('Five', 5), ('Six', 6)]
>>> [term for pair in zip(a,b) for term in pair]
['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]

或使用itertools.chain

>>> from itertools import chain
>>> list(chain.from_iterable(zip(a,b)))
['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]

答案 1 :(得分:4)

In [124]: l=["Three","Four","Five","Six"]

In [125]: [x for x in itertools.chain(*zip(l, range(3,7)))]
Out[125]: ['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]