본문 바로가기
C.W.K.
Stream
Lesson 01 of 06 · published

collections — 기본 자료구조가 어색할 때

~22 min · collections, deque, counter, defaultdict, namedtuple

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

deque는 양쪽 끝이 빠르다

리스트의 오른쪽 append/pop은 O(1)이지만 왼쪽은 원소를 밀어야 해. deque는 양쪽이 O(1)이라 큐·BFS·이동 창에 맞고, maxlen으로 오래된 값을 자동으로 버릴 수 있어.

Counter와 defaultdict

Counter는 빈도를 세고 most_common과 카운터 연산을 제공해. defaultdict는 누락 키에 처음 접근할 때 팩토리로 값을 만들어 그룹 묶기 같은 코드를 단순하게 해.

namedtuple과 다른 도구

가볍고 불변인 위치 레코드에는 namedtuple, 기본값·타입·행동이 더 필요하면 dataclass를 써. ChainMap과 OrderedDict도 특정한 겹친 매핑·순서 조작에 남아 있어.

Code

양쪽 끝이 빠른 deque·python
from collections import deque

q = deque([1, 2, 3])
q.append(4)               # 오른쪽
q.appendleft(0)           # 왼쪽
print(q)                  # deque([0, 1, 2, 3, 4])

q.pop()                   # 오른쪽
q.popleft()               # 왼쪽
print(q)                  # deque([1, 2, 3])

# Bounded ring buffer
recent = deque(maxlen=3)
for x in [1, 2, 3, 4, 5]:
    recent.append(x)
print(recent)             # deque([3, 4, 5], maxlen=3)
빈도를 세는 Counter·python
from collections import Counter

text = "the quick brown fox jumps over the lazy dog the"
words = text.split()

c = Counter(words)
print(c)                  # Counter({'the': 3, ...})
print(c.most_common(3))   # [('the', 3), ('quick', 1), ('brown', 1)]

# Counter 가 산술 지원
a = Counter("hello")
b = Counter("world")
print(a + b)              # Counter({'l': 3, 'o': 2, ...})
print(a - b)              # 양수만 — a 에 있고 b 에 없는 글자

# 누락 키 0 반환, KeyError 없음
print(c["nonexistent"])   # 0
누락값을 자동 생성하는 defaultdict·python
from collections import defaultdict

# 첫 글자로 그룹핑
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
groups = defaultdict(list)
for w in words:
    groups[w[0]].append(w)        # defaultdict 덕분에 작동

print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}

# 카운터 use case
counts = defaultdict(int)
for c in "hello world":
    counts[c] += 1                 # int() = 0 — 0 으로 자동 init

print(dict(counts))
ChainMap과 OrderedDict가 필요한 경우·python
from collections import ChainMap, OrderedDict

# ChainMap — 여러 dict 를 하나로 (lookup-only)
defaults = {"theme": "dark", "font": "mono"}
user = {"theme": "light"}
combined = ChainMap(user, defaults)
print(combined["theme"])      # 'light'    — user 이김
print(combined["font"])       # 'mono'     — defaults 로 fall through

# OrderedDict — 3.7 이전엔 유용. 이젠 일반 dict 가 삽입 순서.
# 명시적 reorder 위한 .move_to_end() 는 여전.
od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
od.move_to_end("a")
print(list(od))               # ['b', 'c', 'a']

External links

Exercise

주어진 문장의 단어를 Counter로 세어 가장 흔한 세 개를 찾고, defaultdict(list)로 첫 글자별로 묶어. deque(maxlen=5)로는 순회 중 마지막 다섯 단어만 남겨 세 결과를 출력해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.