Python의 collections 모듈은 파이썬의 built-in 자료구조를 확장한 special container 클래스들을 제공함.
1. Counter
- 요소의 개수를 세는 dictionary의 subclass.
- 해시 가능한 객체의 카운트를 저장함.
from collections import Counter
c = Counter(['apple', 'orange', 'apple', 'banana', 'apple'])
print(c) # Counter({'apple': 3, 'orange': 1, 'banana': 1})
2. defaultdict:
- 기본값을 제공하는 dictionary의 subclass.
- 존재하지 않는 키에 접근할 때 에러 대신 기본값을 반환.
from collections import defaultdict
d = defaultdict(int) # 기본값으로 0을 사용
d['a'] += 1 # 키가 없어도 에러 없이 1이 저장됨
3. OrderedDict:
- 항목이 추가된 순서를 기억하는 dictionary의 subclass.
- Python 3.7부터 built-in
dict
도 순서를 보존함. OrderedDict
는 약간의 추가 기능이 있으며 PyTorch등에서 모델의 저장 및 로드를 위한 자료구조(state_dict)로 사용됨.
from collections import OrderedDict
d = OrderedDict([('a', 1), ('b', 2)])
2025.04.04 - [Python] - [Py] collection.OrderedDict
[Py] collection.OrderedDict
OrderedDict는 삽입된 순서를 보존하는 기능을 추가한 일종의 dict임.collections 모듈에서 제공.Python 3.7부터 built-in dict도 삽입 순서를 보존하게 되었음.하지만 OrderedDict는 그 외에 몇 가지 중요한 추가
ds31x.tistory.com
4. namedtuple:
- 이름이 있는 field를 가진
tuple
의 subclass 를 생성하는 factory function임. - 생성된 객체는
type
형의 객체로tuple
을 상속하고 있는 subclass임:mro()
로 확인 가능.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20
print(type(Point)) # <class 'type'>
print(Point.mro()) # [<class '__main__.Point'>, <class 'tuple'>, <class 'object'>]
2025.04.04 - [Python] - [Py] collections.namedtuple-Factory Function
[Py] collections.namedtuple-Factory Function
1. 팩토리 함수(Factory Function)란?팩토리 함수는 객체 생성 과정을 추상화하여 객체를 생성하는 함수 를 가리킴.즉, 객체를 직접 생성하는 대신 함수를 호출하여 객체를 생성하는 방식으로 다음과
ds31x.tistory.com
5. deque:
- 양쪽 끝에서 효율적으로 추가/제거할 수 있는 기능을 가짐.
list
와 비슷한 용도로 사용가능.
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0) # 왼쪽에 추가
d.append(4) # 오른쪽에 추가
print(d) # deque([0, 1, 2, 3, 4])
6. ChainMap:
- 여러 mapping type의 객체를 단일 view로 그룹화를 가능하게 해줌.
- 여러 dictionary를 chain(연결)하여 하나의 dictionary처럼 사용하도록 해 줌.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'b': 4}
chain = ChainMap(dict1, dict2)
print(chain['b']) # 2 (첫 번째 매핑에서 찾음)
2025.04.04 - [Python] - [Py] collections.ChainMap
[Py] collections.ChainMap
1. ChainMap 이란?ChainMap은 Python의 collections 모듈에서 제공하는 클래스로,여러 매핑(딕셔너리 등)을 단일 뷰로 그룹화하는 기능을 제공.ChainMap은 여러 딕셔너리를 연결(chain)하여 마치 하나의 딕셔너
ds31x.tistory.com
7. UserDict, UserList, UserString:
- built-in container (
dict, list, str
)를 직접 상속하는 대신, 이들을 내부에 캡슐화하여 확장할 수 있는 Wrapper 클래스. - 사용자 정의 메서드를 더 쉽게 추가하거나 기존 동작을 변경할 때 유용함.
- 내부적으로 실제 데이터는 data 속성에 저장됨.
이들 Wrapper 클래스들은 built-in container를 직접 상속할 때 발생할 수 있는 다음의 문제를 피하면서도 해당 컨테이너의 모든 기능을 활용할 수 있게 해주는 장점을 가짐.
- built-in container의 경우, C로 구현체의 바인딩이기 때문에 내부 동작이 불투명하며 Python에서 완전한 접근이 어려움.
- 때문에 method overrding 이 일반적인 Python 클래스와 다르게 동작할 수 있고, super-class에 대한 proxy를 얻는
super()
호출에서 예측불가능한 동작이 발생할 수도 있음. - CPython이 아닌 다른 언어로 만들어진 Python VM에서 동작이 다를 수도 있음.
- 때문에 built-in container를 내부의 attribute로 관리하고 필요한 인터페이스만을 제공하는 Wrapper 클래스인
UserDict, UserList, UserString
이 권장됨.
from collections import UserDict
class MyCustomDict(UserDict):
def __setitem__(self, key, value):
# 키는 항상 소문자로 저장
if isinstance(key, str):
key = key.lower()
# 정수 값은 문자열로 변환하여 저장
if isinstance(value, int):
value = str(value)
# 내부 data 딕셔너리에 저장 (UserDict에서 관리)
super().__setitem__(key, value)
def display_items(self):
"""항목들을 정렬하여 출력하는 부가 기능"""
for key in sorted(self.keys()):
print(f"{key}: {self[key]}")
# 사용 예시
custom_dict = MyCustomDict()
# 키는 소문자로 변환됨
custom_dict['Name'] = 'John'
custom_dict['AGE'] = 30 # 정수는 문자열로 변환됨
# 직접 추가 메서드 호출
custom_dict.display_items() # name: John, age: 30 순서로 출력
# 일반 딕셔너리 메서드도 전부 사용 가능
print(custom_dict.keys()) # dict_keys(['name', 'age'])
print('name' in custom_dict) # True
print(custom_dict.get('age')) # '30' (문자열로 변환됨)
8. abc.ABC 및 abstract (base) classes:
collections.abc
에는 abstarct base class들이 정의됨.- Container,
- Hashable,
- Iterable,
- Iterator,
- 그외 여러가지.
2024.04.15 - [Python] - [Python] collections.abc
[Python] collections.abc
2023.10.06 - [Pages] - [Python] Collectionscollections.abc 와 Python의 DataStructure.Python의 Data structure는 실제적으로 collections.abc 라는 abstract base class (abc) mechanism를 통한 hierarchy로 구성된다: type은 module임.일반적
ds31x.tistory.com
같이보면 좋은 자료들
2023.10.06 - [Pages] - [Python] Collections
[Python] Collections
collections.abc2024.04.15 - [분류 전체보기] - [Python] collections.abc [Python] collections.abc2023.10.06 - [Pages] - [Python] Collections collections.abc 와 Python의 DataStructure. Python의 Data structure는 실제적으로 collections.abc 라
ds31x.tistory.com
2023.10.06 - [분류 전체보기] - [Summary] Python 정리
[Summary] Python 정리
Programming Language and Python 소개2023.10.23 - [Python] - [Python] Programming Language and Introduction of Python. [Python] Programming Language and Introduction of Python.Computer and Program https://dsaint31.tistory.com/436 [CE] Computer and Progra
ds31x.tistory.com
'Python' 카테고리의 다른 글
[Py] collections.namedtuple-Factory Function (0) | 2025.04.04 |
---|---|
[Py] collection.OrderedDict (0) | 2025.04.04 |
[Py] print 함수 (0) | 2025.04.02 |
[PyTorch] autograd 심화: grad_fn 과 custom operation 만들기 (0) | 2025.03.28 |
[Py] Bitwise Operator (0) | 2025.03.26 |