C.W.K.
Stream
Lesson 01 of 06 · published

collections — deque / Counter / defaultdict / namedtuple

~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

표준 라이브러리에서 Pythonist 의 첫 정거장

listdict 가 모든 거 커버하면 collections 절대 안 필요. 안 함. 모듈이 기본 타입이 어색한 문제용 특화 자료구조 줘 — 앞에서 pop 해야 하는 큐, 뭔가 얼마나 자주 나오는지 카운터, 첫 접근 시 자동 채우는 dict, 이름 있는 필드 가진 tuple.

deque — 양쪽 끝 큐

list 는 오른쪽 끝 추가/pop 빠름 (O(1)) + 왼쪽 느림 (O(n)). deque 는 양쪽 다 O(1). 큐 (FIFO), 슬라이딩 윈도우, BFS — 왼쪽 연산이 싸야 하는 모든 거에 사용. deque(maxlen=N) 가 가득 차면 다른 끝에서 자동 버리는 bounded ring buffer.

Counter — 카운팅 쉽게

Counter(iterable) 가 발생 카운트. 결과는 dict 서브클래스 + .most_common(n), 카운터 간 더하기/빼기, 누락 키 0 반환. 손으로 짠 카운트 루프 깔끔히 대체.

defaultdict — 첫 접근 시 자동 채움

defaultdict(list)d[missing_key] 시 factory 호출하고 결과 삽입 후 반환하는 dict. 그룹핑에 완벽 — groups[key].append(item) 그냥 작동, setdefault dance 없음. factory 로 0-인자 callable 뭐든 가능.

namedtuple — 그리고 dataclass 가 더 좋을 수도

data 트랙에서 namedtuple 봤어. 싸고 immutable 한 tuple-shape 레코드엔 여전히 유용. 더 풍부한 필요 (디폴트, 메서드, 타입 어노테이션) 엔 dataclass. 선택은 모양 — 순수 tuple = namedtuple, 동작 있는 레코드 = dataclass.

원칙: 기본 타입이 어색해지기 시작하면 collections 손에 닿아. 여기 모든 named 구조가 Python 작가들이 다듬은 패턴 표현. 어렵게 deque 필요한 거 발견할 필요 없어.

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 X
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

단어 list — words = "the quick brown fox jumps over the lazy dog the quick fox".split(). (a) Counter 로 가장 흔한 단어 3 개 찾기. (b) defaultdict(list) 로 첫 글자로 단어 그룹핑. (c) deque(maxlen=5) 로 list 순회하면서 본 마지막 5 단어만 유지. 셋 다 출력.

Progress

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

댓글 0

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

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