我需要迭代一个循环列表,可能多次,每次从最后访问的项目开始.
用例是连接池.客户端请求连接,迭代器检查指向的连接是否可用并返回它,否则循环直到找到可用的连接.
有没有一种巧妙的方法在Python中做到这一点?
使用 itertools.cycle ,这是它的确切目的:from itertools import cycle lst = ['a', 'b', 'c'] pool = cycle(lst) for item in pool: print item,
输出:
a b c a b c ...
(显然是永远的循环)
为了手动推进迭代器并逐个拉取值,只需调用 next(pool) :
>>> next(pool) 'a' >>> next(pool) 'b'
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did171364