Python中的循环列表迭代器 [英] Circular list iterator in Python
本文介绍了Python中的循环列表迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要遍历一个循环列表,可能多次,每次从最后一个访问项开始。
I need to iterate over a circular list, possibly many times, each time starting with the last visited item.
用例是一个连接池。客户端请求连接,迭代器检查指向的连接是否可用并返回它,否则循环直到找到可用的连接。
The use case is a connection pool. A client asks for connection, an iterator checks if pointed-to connection is available and returns it, otherwise loops until it finds one that is available.
是否有一个整洁的方式在Python中做到这一点?
Is there a neat way to do it in Python?
推荐答案
使用 itertools.cycle
,这就是它的确切目的:
Use itertools.cycle
, that's its exact purpose:
from itertools import cycle
lst = ['a', 'b', 'c']
pool = cycle(lst)
for item in pool:
print item,
输出:
a b c a b c ...
(显然是循环)
为了手动推进迭代器并逐个拉取值,只需调用 下一个(游泳池)
:
In order to manually advance the iterator and pull values from it one by one, simply call next(pool)
:
>>> next(pool)
'a'
>>> next(pool)
'b'
这篇关于Python中的循环列表迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文