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

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

本文介绍了python中两个列表混合的循环方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果输入是

round_robin(range(5), "hello")

我需要输出为

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

我试过了

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

但它给出了错误

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

如何修改代码得到想要的输出?

How to modify the code to get the desired output?

推荐答案

您可以在这里找到一系列迭代方案:http://docs.python.org/2.7/library/itertools.html#recipes

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

编辑: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"))

这篇关于python中两个列表混合的循环方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:11