PYTHON · 컬렉션
collections 모듈 — Counter, deque, namedtuple
표준 라이브러리의 강력한 컬렉션 타입을 활용합니다.
컬렉션중급CounterdequenamedtupleNamedTuplecollections
핵심 설명
표준 라이브러리의 강력한 컬렉션 타입을 활용합니다.
Python code
from collections import Counter, deque, namedtuple, OrderedDict
# Counter — 빈도 계산
text = "python programming is fun and python is easy"
word_count = Counter(text.split())
print(word_count.most_common(3))
# [('python', 2), ('is', 2), ('programming', 1)]
c1 = Counter("apple")
c2 = Counter("pear")
print(c1 + c2) # Counter({'p':2,'a':2,'e':1,'l':1,'r':1})
print(c1 & c2) # 교집합
# deque — 양방향 큐 (O(1) 추가/삭제)
dq = deque([1, 2, 3], maxlen=5)
dq.appendleft(0) # [0, 1, 2, 3]
dq.append(4) # [0, 1, 2, 3, 4]
dq.rotate(1) # [4, 0, 1, 2, 3]
# namedtuple — 이름 있는 튜플
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p._asdict()) # {'x': 3, 'y': 4}
# typing.NamedTuple — 타입 힌트 버전 (권장)
from typing import NamedTuple
class Employee(NamedTuple):
name: str
dept: str
salary: float = 50000.0
emp = Employee("Alice", "Engineering")
print(emp) # Employee(name='Alice', dept='Engineering', salary=50000.0)학습 팁
deque는 리스트 앞에 원소를 추가할 때 O(n)인 리스트와 달리 O(1)입니다. 큐나 최근 N개 항목 유지에 사용하세요.
주의할 점
Counter에서 없는 키를 조회하면 KeyError 대신 0을 반환합니다. 이 점이 일반 딕셔너리와 다릅니다.
자주 묻는 질문
collections 모듈 — Counter, deque, namedtuple란 무엇인가요?
표준 라이브러리의 강력한 컬렉션 타입을 활용합니다.
collections 모듈 — Counter, deque, namedtuple 학습 시 주의할 점은 무엇인가요?
Counter 에서 없는 키를 조회하면 KeyError 대신 0 을 반환합니다. 이 점이 일반 딕셔너리와 다릅니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.