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

2024-06-01 00:39:11 发布

您现在位置: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__'

如何修改代码以获得所需的输出?


Tags: nameinhelloforlendefitemsrange
3条回答

您可以使用^{}函数,然后使用列表理解将结果展平,如下所示

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

输出

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

zip函数对两个iterable中的值进行分组,如下所示

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

我们把每一个元组都取出来,用列表理解的方法把它展平。

但是正如@Ashwini Chaudhary建议的那样,使用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"))

你可以在这里找到一系列迭代食谱: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"))

您可以利用itertools.chain(展开元组)和itertools.izip(为了创建交错模式而转置元素)来创建结果

>>> from itertools import izip, chain
>>> list(chain.from_iterable(izip(range(5), "hello")))
[0, 'h', 1, 'e', 2, 'l', 3, 'l', 4, 'o']

如果字符串的长度不等,请使用带pad值的izip_longest(最好是空字符串)

相关问题 更多 >