use*_*854 86 python iterator list
我需要迭代一个循环列表,可能多次,每次从最后访问的项目开始.
用例是连接池.客户端请求连接,迭代器检查指向的连接是否可用并返回它,否则循环直到找到可用的连接.
有没有一种巧妙的方法在Python中做到这一点?
Luk*_*raf 137
使用itertools.cycle
,这是它的确切目的:
from itertools import cycle
lst = ['a', 'b', 'c']
pool = cycle(lst)
for item in pool:
print item,
Run Code Online (Sandbox Code Playgroud)
输出:
a b c a b c ...
Run Code Online (Sandbox Code Playgroud)
(显然是永远的循环)
为了手动推进迭代器并逐个拉取值,只需调用next(pool)
:
>>> next(pool)
'a'
>>> next(pool)
'b'
Run Code Online (Sandbox Code Playgroud)
Jac*_*all 45
正确的答案是使用itertools.cycle.但是,我们假设库函数不存在.你会如何实现它?
使用发电机:
def circular():
while True:
for connection in ['a', 'b', 'c']:
yield connection
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用for
语句进行无限迭代,也可以调用next()
以从生成器迭代器获取单个下一个值:
connections = circular()
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
#....
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
conn = ['a', 'b', 'c', 'c', 'e', 'f']
conn_len = len(conn)
index = 0
while True:
print(conn[index])
index = (index + 1) % conn_len
Run Code Online (Sandbox Code Playgroud)
打印abcdefab c ...永远
你可以用append(pop())
循环来完成这个:
l = ['a','b','c','d']
while True:
print l[0]
l.append(l.pop(0))
Run Code Online (Sandbox Code Playgroud)
或for i in range()
循环:
l = ['a','b','c','d']
ll = len(l)
while True:
for i in range(ll):
print l[i]
Run Code Online (Sandbox Code Playgroud)
或者干脆:
l = ['a','b','c','d']
while True:
for i in l:
print i
Run Code Online (Sandbox Code Playgroud)
所有这些打印:
>>>
a
b
c
d
a
b
c
d
...etc.
Run Code Online (Sandbox Code Playgroud)
在这三个中,我倾向于将 append(pop()) 方法作为函数
servers = ['a','b','c','d']
def rotate_servers(servers):
servers.append(servers.pop(0))
return servers
while True:
servers = rotate_servers(servers)
print servers[0]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45122 次 |
最近记录: |