codefreak codefreak - 1 year ago 104
Python Question

Round Robin method of mixing of two lists in python

If input is

round_robin(range(5), "hello")

i need o/p as

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

I tried

def round_robin(*seqs):
list1= cycle(iter(items).__name__ for items in seqs)
while length:
for x in list1:
yield x
except StopIteration:
length -= 1


but it gives error as

AttributeError: 'listiterator' object has no attribute '__name__'

How to modify the code to get the desired o/p

Answer Source

You could find a series of iteration recipes here:

from itertools import islice, cycle

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:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

print list(roundrobin(range(5), "hello"))