Python/Python 심화

Python collections 모듈을 이용한 데이터 구조

임베디드 친구 2025. 7. 23. 19:58
728x90
반응형

Python collections 모듈을 이용한 데이터 구조

Python은 내장 데이터 구조인 리스트, 튜플, 딕셔너리, 세트를 제공하여 다양한 데이터를 효과적으로 처리할 수 있도록 돕습니다. 그러나 Python의 표준 라이브러리에는 collections 모듈이라는 강력한 도구가 포함되어 있어, 이러한 데이터 구조를 확장하거나 대체할 수 있는 다양한 클래스가 제공됩니다.

이 글에서는 collections 모듈의 주요 클래스와 이를 활용한 실용적인 예제를 살펴보겠습니다.


1. namedtuple: 이름이 있는 튜플

namedtuple은 일반 튜플에 이름을 부여하여 더 읽기 쉽고 구조적인 데이터를 다룰 수 있도록 돕습니다.

사용법

from collections import namedtuple

# namedtuple 정의
Point = namedtuple('Point', ['x', 'y'])

# namedtuple 인스턴스 생성
p = Point(10, 20)

print(p.x)  # 10
print(p.y)  # 20

활용 예제: 2D 좌표 계산

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])

def calculate_distance(p1, p2):
    return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5

p1 = Point(0, 0)
p2 = Point(3, 4)

print(f"두 점 사이의 거리: {calculate_distance(p1, p2)}")

2. deque: 빠른 양방향 큐

deque는 양쪽 끝에서 빠르게 삽입 및 삭제가 가능한 큐입니다. 리스트보다 효율적으로 큐 작업을 수행합니다.

사용법

from collections import deque

# deque 생성
dq = deque([1, 2, 3])

# 요소 추가
dq.append(4)        # 오른쪽에 추가
dq.appendleft(0)    # 왼쪽에 추가

# 요소 제거
dq.pop()            # 오른쪽에서 제거
dq.popleft()        # 왼쪽에서 제거

print(dq)  # deque([1, 2, 3])

활용 예제: 회전하는 큐

from collections import deque

dq = deque(['a', 'b', 'c', 'd'])

# 큐 회전
dq.rotate(1)  # 오른쪽으로 한 칸 회전
print(dq)  # deque(['d', 'a', 'b', 'c'])

dq.rotate(-2) # 왼쪽으로 두 칸 회전
print(dq)  # deque(['b', 'c', 'd', 'a'])

3. Counter: 아이템 개수 세기

Counter는 iterable 객체에서 요소의 개수를 자동으로 셀 수 있는 딕셔너리 서브클래스입니다.

사용법

from collections import Counter

# 문자열에서 문자 개수 세기
counter = Counter('hello world')
print(counter)  # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

활용 예제: 단어 빈도 분석

from collections import Counter

text = "apple orange banana apple orange apple"
words = text.split()

counter = Counter(words)
print(counter)  # Counter({'apple': 3, 'orange': 2, 'banana': 1})

# 가장 흔한 단어
most_common = counter.most_common(1)
print(most_common)  # [('apple', 3)]

4. defaultdict: 기본값이 있는 딕셔너리

defaultdict는 키가 없을 경우 기본값을 제공하는 딕셔너리입니다.

사용법

from collections import defaultdict

# 기본값이 리스트인 defaultdict 생성
dd = defaultdict(list)

dd['a'].append(1)
dd['b'].append(2)
dd['a'].append(3)

print(dd)  # defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2]})

활용 예제: 그룹화

from collections import defaultdict

data = [('apple', 1), ('banana', 2), ('apple', 3), ('banana', 4), ('cherry', 5)]

grouped_data = defaultdict(list)
for key, value in data:
    grouped_data[key].append(value)

print(grouped_data)
# defaultdict(<class 'list'>, {'apple': [1, 3], 'banana': [2, 4], 'cherry': [5]})

5. OrderedDict: 순서가 있는 딕셔너리

Python 3.7 이후로 기본 딕셔너리도 삽입 순서를 유지하지만, OrderedDict는 그 이전 버전과의 호환성을 위해 사용됩니다. 또한, 일부 추가 기능을 제공합니다.

사용법

from collections import OrderedDict

# OrderedDict 생성
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3

print(od)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

활용 예제: LRU 캐시 구현

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key):
        if key in self.cache:
            self.cache.move_to_end(key)
            return self.cache[key]
        return -1

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        elif len(self.cache) >= self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = value

cache = LRUCache(2)
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1))  # 1
cache.put(3, 3)
print(cache.get(2))  # -1 (삭제됨)

6. ChainMap: 다중 딕셔너리 뷰

ChainMap은 여러 딕셔너리를 연결하여 하나의 뷰로 제공합니다.

사용법

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

chain = ChainMap(dict1, dict2)
print(chain['a'])  # 1 (dict1에서 검색)
print(chain['b'])  # 2 (dict1에서 검색)
print(chain['c'])  # 4 (dict2에서 검색)

결론

Python의 collections 모듈은 고급 데이터 구조를 제공하여 복잡한 데이터를 더 쉽게 다룰 수 있게 해줍니다. namedtuple, deque, Counter, defaultdict, OrderedDict, ChainMap 등의 클래스는 다양한 상황에서 효율적이고 간결한 코드를 작성할 수 있는 강력한 도구입니다.

이제 여러분도 collections를 활용하여 더 효율적이고 직관적인 코드를 작성해 보세요!

728x90
반응형