Round Robin method of mixing of two lists in python
You can use zip
function and then flatten the result with list comprehension, like this
def round_robin(first, second):
return[item for items in zip(first, second) for item in items]
print round_robin(range(5), "hello")
Output
[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
zip
function groups the values from both the iterables, like this
print zip(range(5), "hello") # [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
We take each and every tuple and flatten it out with list comprehension.
But as @Ashwini Chaudhary suggested, use roundrobin receipe from the docs
from itertools import cycle
from itertools import 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))
print list(roundrobin(range(5), "hello"))
You could find a series of iteration recipes here: http://docs.python.org/2.7/library/itertools.html#recipes
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:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
print list(roundrobin(range(5), "hello"))
EDIT: Python 3
https://docs.python.org/3/library/itertools.html#itertools-recipes
def 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:
num_active -= 1
nexts = cycle(islice(nexts, num_active))
print list(roundrobin(range(5), "hello"))
You can leverage itertools.chain (to unwrap the tuples) with itertools.izip (to transpose the elements in order to create an interleaving pattern) to create your result
>>> from itertools import izip, chain
>>> list(chain.from_iterable(izip(range(5), "hello")))
[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
If the strings are of unequal length, use izip_longest with a pad value (preferably empty string)