gpt4 book ai didi

python - python中两个列表混合的Round Robin方法

转载 作者:太空狗 更新时间:2023-10-29 21:31:51 24 4
gpt4 key购买 nike

如果输入是

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__'

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

最佳答案

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

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 函数将来自两个可迭代对象的值分组,如下所示

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

关于python - python中两个列表混合的Round Robin方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21062532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com