python – Pythonic way to combine two lists in an alternating fashion?
python – Pythonic way to combine two lists in an alternating fashion?
Heres one way to do it by slicing:
>>> list1 = [f, o, o]
>>> list2 = [hello, world]
>>> result = [None]*(len(list1)+len(list2))
>>> result[::2] = list1
>>> result[1::2] = list2
>>> result
[f, hello, o, world, o]
Theres a recipe for this in the itertools
documentation:
from itertools import cycle, islice
def roundrobin(*iterables):
roundrobin(ABC, D, EF) --> A D E B F C
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
EDIT:
For pythons version greater than 3:
from itertools import cycle, islice
def roundrobin(*iterables):
roundrobin(ABC, D, EF) --> A D E B F C
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
python – Pythonic way to combine two lists in an alternating fashion?
import itertools
print [x for x in itertools.chain.from_iterable(itertools.izip_longest(list1,list2)) if x]
I think this is the most pythonic way of doing it.