Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

Round Robin method of mixing of two lists in python

If input is

round_robin(range(5), "hello")

I need output as

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

I tried

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

pass

but it gives error as

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

How to modify the code to get the desired output?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...