使用itertools.cycle()在多个列表之间循环 [英] cycle through multiple list using itertools.cycle()

查看:95
本文介绍了使用itertools.cycle()在多个列表之间循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器列表.每个服务器上都有一个名称列表. 例如:

I have a list of servers. Every server has a list of name on it. example:

server1 = ['a','b','c']
server2 = ['d','e','f']
server3 = ['g','h','i']

我想按服务器名称而不是按服务器进行迭代.例如,在server1中选择'a'后,移至'd'(不是'b'),依此类推.如果要使用itertools.cycle(),是否需要创建服务器列表以进行循环?我的预期结果是['a','d','g','b','e','h','c','f','i'].你能给我一个简单的例子,关于如何循环多个列表.

I want to iterate per server name not per server. For example after picking 'a' in server1, move to 'd' (not 'b') and so on. If I'm going to use itertools.cycle(), do I have to create a list of server to cycle through? My expected result is ['a','d','g','b','e','h','c','f','i']. Can you give me a simple example on how to cycle in multiple list.

推荐答案

这很好用:

>>> from itertools import chain, islice, izip, cycle
>>> list(islice(cycle(chain.from_iterable(izip(server1, server2, server3))), 0, 18))
['a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i', 'a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i']

请注意,listislice只是出于演示目的,用于显示某些内容并防止无限输出...

Note, the list and islice are just for demonstration purposes to give something to display and prevent infinite output...

现在,如果长度列表不相等,它将变得更加有趣.然后izip_longest将成为您的朋友,但此时可能值得使用以下功能:

Now, it gets more interesting if you have unequal length lists. Then izip_longest will be your friend, but it might be worth a function at this point:

import itertools
def cycle_through_servers(*server_lists):
    zipped = itertools.izip_longest(*server_lists, fillvalue=None)
    chained = itertools.chain.from_iterable(zipped)
    return itertools.cycle(s for s in chained if s is not None)

演示:

>>> from itertools import islice
>>> server3 = ['g', 'h', 'i', 'j']
>>> list(islice(cycle_through_servers(server1, server2, server3), 0, 20))
['a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i', 'j', 'a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i', 'j']

这篇关于使用itertools.cycle()在多个列表之间循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆