好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python中的循环列表迭代器

我需要迭代一个循环列表,可能多次,每次从最后访问的项目开始.

用例是连接池.客户端请求连接,迭代器检查指向的连接是否可用并返回它,否则循环直到找到可用的连接.

有没有一种巧妙的方法在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'

查看更多关于Python中的循环列表迭代器的详细内容...

  阅读:18次