Quantcast
Viewing latest article 27
Browse Latest Browse All 49

Answer by David Z for Pythonic way to combine (interleave, interlace, intertwine) two lists in an alternating fashion?

There's a recipe for this in the itertools documentation (note: for Python 3):

from itertools import cycle, islicedef roundrobin(*iterables):"roundrobin('ABC', 'D', 'EF') --> A D E B F C"    # Recipe credited to George Sakkis    num_active = len(iterables)    nexts = cycle(iter(it).__next__ for it in iterables)    while num_active:        try:            for next in nexts:                yield next()        except StopIteration:            # Remove the iterator we just exhausted from the cycle.            num_active -= 1            nexts = cycle(islice(nexts, num_active))

Viewing latest article 27
Browse Latest Browse All 49

Trending Articles