我想打开这个列表:
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 不会以此为荣。有没有更短的方法?
我可能会做这样的事情:
>>> 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]
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]