기본 콘텐츠로 건너뛰기

파이썬(Python) 데크(Deque) 자료구조

Deque(데크)는 Double-Ended Queue 의 줄임말로, 아래 그림과 같이 자료의 앞(왼쪽)과 뒤(오른쪽) 즉, 양방향에서 데이터를 처리할 수 있는 Queue형 자료구조이다.

List(리스트)와 비슷하지만, 컨테이너의 앞과 뒤에서 원소를 삽입, 제거하는 것이 빠르다.


<Deque 구조>

Python에서는 collections 라이브러리를 통해 쉽게 이용할 수 있다.

collections.deque의 기본 문법은 아래와 같다.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from collections import deque

friends_list = ["john", "jane", "peter"]

friends_deq = deque(friends_list)
print(friends_deq)

# 오른쪽(마지막)에 추가
friends_deq.append("daniel")
print(friends_deq)

# 왼쪽(첫 번째)에 추가
friends_deq.appendleft("young")
print(friends_deq)

# 모든 요소들 앞으로 당기거나 밀어내기
friends_deq.rotate(2)
print(friends_deq)

friends_deq.rotate(-2)
print(friends_deq)

# 오른쪽(마지막) 삭제 & 반환
print(friends_deq.pop())
print(friends_deq)

# 왼쪽(첫 번째) 삭제 & 반환
print(friends_deq.popleft())
print(friends_deq)

끝.

댓글