Circulaire lijst iterator in Python

Ik moet een cirkelvormige lijst herhalen, mogelijk vele malen, elke keer beginnend met het laatst bezochte item.

De use case is een verbindingspool. Een client vraagt ​​om verbinding, een iterator controleert of er een point-to-verbinding beschikbaar is en retourneert deze, anders loopt hij door totdat hij er een vindt die beschikbaar is.

Is er een nette manier om dit in Python te doen?


Antwoord 1, autoriteit 100%

Gebruik itertools.cycle, dat is precies het doel:

from itertools import cycle
lst = ['a', 'b', 'c']
pool = cycle(lst)
for item in pool:
    print item,

Uitvoer:

a b c a b c ...

(Voor altijd in een lus, uiteraard)


Als u de iterator handmatig wilt voortzetten en er één voor één waarden uit wilt halen, belt u gewoon next(pool):

>>> next(pool)
'a'
>>> next(pool)
'b'

Antwoord 2, autoriteit 30%

Het juiste antwoord is om itertools.cyclete gebruiken. Maar laten we aannemen dat de bibliotheekfunctie niet bestaat. Hoe zou je het implementeren?

Gebruik een generator:

def circular():
    while True:
        for connection in ['a', 'b', 'c']:
            yield connection

Vervolgens kunt u een forgebruiken statement oneindig herhalen, of u kunt next()aanroepen om haal de enkele volgende waarde uit de generator-iterator:

connections = circular()
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
#....

Antwoord 3, autoriteit 6%

Of je kunt het als volgt doen:

conn = ['a', 'b', 'c', 'd', 'e', 'f']
conn_len = len(conn)
index = 0
while True:
    print(conn[index])
    index = (index + 1) % conn_len

print a b c d e f a b c… voor altijd


Antwoord 4, autoriteit 2%

u kunt dit bereiken met append(pop())loop:

l = ['a','b','c','d']
while True:
    print l[0]
    l.append(l.pop(0))

of for i in range()loop:

l = ['a','b','c','d']
ll = len(l)
while True:
    for i in range(ll):
       print l[i]

of gewoon:

l = ['a','b','c','d']
while True:
    for i in l:
       print i

die allemaal worden afgedrukt:

>>>
a
b
c
d
a
b
c
d
...etc.

van de drie zou ik gevoelig zijn voor de append(pop())-benadering als functie

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]

Other episodes