I want to turn this list:
l=["Three","Four","Five","Six"]
into this one:
['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6]
and I used this code (which works well) to do it:
for i,j in zip(range(1,len(l)*2,2),range(3,7)*2):
l.insert(i,j)
But I guess Python would not be proud of it. Is there a shorter way for this?
I might do something like this:
>>> 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]
or, using 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With