5.1.2. Using Lists as Queues

리스트를 큐처럼 사용하기


It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
리스트를 큐처럼 사용할 수도 있습니다. 큐 queue 란 첫번째로 추가된 요소가 첫번째로 회수되는 것입니다. ("first-in, first-out") 하지만 큐는 리스트에 잘 맞는 방식은 아닙니다. .append( )와 .pop( )으로 리스트의 마지막 부분을 넣고 빼는 것은 빠릅니다만, .insert( )와 .pop( )으로 리스트의 가장 앞 부분을 넣고 빼는 것은 느리기 때문이지요. 리스트의 가장 앞 부분을 변경할 경우 뒤에 있는 모든 항목들이 옮겨져야 하기 때문에 그렇습니다.

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
큐를 사용하려면, collections.deque 를 이용하십시오. collections.deque는 appends와 pops 을 리스트의 양쪽 끝에 빠르게 적용하기 위해 만들어졌습니다.

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

참고
deque 는 컨테이너 데이터 유형인 collections 의 객체입니다. 8.3.3에서 보실 수 있습니다. (아직 연결되지 않음)

results matching ""

    No results matching ""