Python 中的循环列表迭代器

2024-03-26

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

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

我怎样才能在Python中巧妙地做到这一点?


If you instead need an immediately created list of the results up to a certain length, rather than iterating on demand: see Repeat list to max number of elements https://stackoverflow.com/questions/39863250 for general techniques, and How to replicate array to specific length array https://stackoverflow.com/questions/45127810 for Numpy-specific techniques.


Use itertools.cycle https://docs.python.org/3/library/itertools.html#itertools.cycle,这就是它的确切目的:

from itertools import cycle

lst = ['a', 'b', 'c']

pool = cycle(lst)

for item in pool:
    print(item)

Output:

a b c a b c ...

(显然,永远循环)


为了手动推进迭代器并从中一一提取值,只需调用next(pool) https://docs.python.org/3/library/functions.html#next:

>>> next(pool)
'a'
>>> next(pool)
'b'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的循环列表迭代器 的相关文章

随机推荐