Python의 순환 목록 반복기
마지막으로 방문한 항목부터 시작하여 순환 목록을 여러 번 반복해야 합니다.
사용 사례는 연결 풀입니다.클라이언트가 접속을 요구하면 반복기는 포인트 투 접속을 사용할 수 있는지 확인하고 반환하며, 그렇지 않으면 사용 가능한 접속을 찾을 때까지 루프합니다.
Python에서는 어떻게 하면 깔끔하게 할 수 있을까요?
필요에 따라 반복하는 것이 아니라 특정 길이의 결과 목록이 즉시 필요한 경우: 일반 기술의 경우 최대 요소 수까지 목록 반복 및 Numpy별 기술의 경우 배열을 특정 길이 배열로 복제하는 방법을 참조하십시오.
를 사용하는 것이 정확한 목적입니다.
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)
'a'
>>> next(pool)
'b'
정답은 itertools.cycle을 사용하는 것입니다.하지만 도서관 기능이 존재하지 않는다고 가정해봅시다.어떻게 구현하시겠습니까?
제너레이터 사용:
def circular():
while True:
for connection in ['a', 'b', 'c']:
yield connection
그런 다음 문을 사용하여 무한 반복하거나 를 호출하여 제너레이터 반복기에서 다음 단일 값을 가져올 수 있습니다.
connections = circular()
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
next(connections) # 'b'
next(connections) # 'c'
next(connections) # 'a'
#....
또는 다음과 같이 할 수 있습니다.
conn = ['a', 'b', 'c', 'd', 'e', 'f']
conn_len = len(conn)
index = 0
while True:
print(conn[index])
index = (index + 1) % conn_len
b c d e f a b c ...를 인쇄합니다.영원히.
이를 실현하기 위해서는append(pop())루프:
l = ['a','b','c','d']
while True:
print l[0]
l.append(l.pop(0))
또는for i in range()루프:
l = ['a','b','c','d']
ll = len(l)
while True:
for i in range(ll):
print l[i]
또는 단순하게:
l = ['a','b','c','d']
while True:
for i in l:
print i
모두 인쇄:
>>>
a
b
c
d
a
b
c
d
...etc.
세 가지 중 하나의 함수로서 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]
사이클을 원하는 경우ntimes,ncycles itertools 레시피:
from itertools import chain, repeat
def ncycles(iterable, n):
"Returns the sequence elements n times"
return chain.from_iterable(repeat(tuple(iterable), n))
list(ncycles(["a", "b", "c"], 3))
# ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
커스텀 리터레이터가 필요합니다.이 답변에서 리터레이터를 수정하겠습니다.
from itertools import cycle
class ConnectionPool():
def __init__(self, ...):
# whatever is appropriate here to initilize
# your data
self.pool = cycle([blah, blah, etc])
def __iter__(self):
return self
def __next__(self):
for connection in self.pool:
if connection.is_available: # or however you spell it
return connection
무한 루프를 피하기 위해 목록 크기가 두 배가 될 때까지 배열 길이를 반복했습니다.독자적인 전제 조건을 실장할 수 있습니다.아이디어는 무한 루프를 피하는 것입니다.
#Implement Circular Linked List
from itertools import cycle
list=[1,2,3,4,5]
lstlength=len(list)*2
print(lstlength)
pool=cycle(list)
i=0
#To avoid infinite loop break when you have iterated twice size of the list
for items in pool:
print(items)
if i >lstlength:
break
i += 1
class A(object):
def __init__(self, l):
self.strt = 0
self.end = len(l)
self.d = l
def __iter__(self):
return self
def __next__(self):
val = None
if self.strt>=self.end:
self.strt=0
val = self.d[self.strt]
self.strt += 1
return val
a= A([8,9,7,66])
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))
관심 있는 분들을 위해서.지정된 색인에서 시작하여 앞으로 또는 뒤로 루프하려면:
def loop_fwd(arr, index):
while True:
arr_index = index % len(arr)
yield arr_index, arr[arr_index]
index += 1
def loop_bcw(arr, index):
while True:
arr_index = index % len(arr)
yield arr_index, arr[arr_index]
index -= 1
forward_it = loop_fwd([1,2,3,4,5], 3)
backward_it = loop_bcw([1,2,3,4,5], 3)
print('forward:')
for i in range(10):
print(next(forward_it))
print('backward:')
for i in range(10):
print(next(backward_it))
언급URL : https://stackoverflow.com/questions/23416381/circular-list-iterator-in-python
'programing' 카테고리의 다른 글
| 어레이 길이를 가져오시겠습니까? (0) | 2023.04.09 |
|---|---|
| Moq + 유닛 테스트 - 시스템반사.TargetParameterCountException: 매개 변수 수가 일치하지 않습니다. (0) | 2023.04.09 |
| 저장된 csv에 인덱스를 생성하는 판다를 피하는 방법 (0) | 2023.04.09 |
| npm을 사용하여 TypeScript를 최신 버전으로 업데이트하려면 어떻게 해야 합니까? (0) | 2023.04.04 |
| Java를 사용하여 부분 JSON 응답을 반환하려면 어떻게 해야 합니까? (0) | 2023.04.04 |