循环方法在python中混合两个列表

cod*_*eak 7 python python-2.7

如果是输入

round_robin(range(5), "hello")
Run Code Online (Sandbox Code Playgroud)

我需要o/p as

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
Run Code Online (Sandbox Code Playgroud)

我试过了

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
Run Code Online (Sandbox Code Playgroud)

但它给出了错误

AttributeError: 'listiterator' object has no attribute '__name__'
Run Code Online (Sandbox Code Playgroud)

如何修改代码以获得所需的o/p

the*_*eye 5

您可以使用zip函数,然后使用列表推导将结果展平,就像这样

def round_robin(first, second):
    return[item for items in zip(first, second) for item in items]
print round_robin(range(5), "hello")
Run Code Online (Sandbox Code Playgroud)

产量

[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']
Run Code Online (Sandbox Code Playgroud)

zip 函数对来自两个迭代的值进行分组,就像这样

print zip(range(5), "hello") # [(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
Run Code Online (Sandbox Code Playgroud)

我们采用每个元组并用列表理解将其展平.

但正如@Ashwini Chaudhary建议的那样,使用文档中的roundrobin receipe

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"))
Run Code Online (Sandbox Code Playgroud)


And*_*rco 5

您可以在这里找到一系列迭代食谱: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"))
Run Code Online (Sandbox Code Playgroud)

编辑: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")))
Run Code Online (Sandbox Code Playgroud)