소개
이 튜토리얼에서는 Python 의 내장 collections 모듈을 살펴보겠습니다. collections 모듈은 리스트, 튜플, 딕셔너리 (dictionaries) 와 같은 Python 의 내장 컨테이너의 기능을 확장하는 다양한 컨테이너 데이터 타입을 제공하는 강력한 라이브러리입니다.
NamedTuple
namedtuple은 튜플의 서브클래스로, 가독성과 자체 문서화 코드를 위해 명명된 필드를 제공합니다. named_tuple.py에서 2D 공간의 점을 나타내는 namedtuple을 만들어 보겠습니다.
## Import collections
from collections import namedtuple
## Define a namedtuple type Point with x and y properties
Point = namedtuple('Point', ['x', 'y'])
## Create a Poinit object
p = Point(1, 2)
## Retrieve the properties of point
print(p.x)
print(p.y)
그런 다음, 터미널에서 스크립트를 실행하십시오.
python named_tuple.py
출력:
1
2
Counter
Counter는 컬렉션 내 요소의 발생 횟수를 세는 dict의 서브클래스입니다. counter.py에서 문자열 내 문자의 발생 횟수를 세는 Counter 객체를 만들어 보겠습니다.
from collections import Counter
text = "hello, world!"
## Gets the number of occurrences of the elements in the collection and returns them as a dictionary
char_count = Counter(text)
print(char_count)
그런 다음, 터미널에서 스크립트를 실행하십시오.
python counter.py
출력:
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ',': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
OrderedDict
OrderedDict는 요소가 삽입된 순서를 유지하는 dict 의 서브클래스입니다. ordered_dict.py에서 OrderedDict를 생성하고 몇 가지 키 - 값 쌍을 추가해 보겠습니다.
from collections import OrderedDict
## Initialdefining OrderedDict
od = OrderedDict()
## Insert in key-value pairs
od['a'] = 1
od['b'] = 2
od['c'] = 3
## Iterate over the key-value pairs and print out the contents
for key, value in od.items():
print(key, value)
그런 다음, 터미널에서 스크립트를 실행하십시오.
python ordered_dict.py
출력:
a 1
b 2
c 3
DefaultDict
Defaultdict(int)
DefaultDict는 존재하지 않는 키에 대한 기본값을 제공하는 dict 의 서브클래스입니다. default_dict1.py에서 기본값 0을 갖는 DefaultDict를 생성하고 문장 내 단어의 발생 횟수를 세어 보겠습니다.
from collections import defaultdict
sentence = "the quick brown fox jumps over the lazy dog"
word_count1 = defaultdict(int)
for word in sentence.split():
## Count the occurrences of words
word_count1[word] += 1
print(dict(word_count1))
그런 다음, 터미널에서 스크립트를 실행하십시오.
python default_dict1.py
출력:
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
DefaultDict를 사용하지 않았다면, 해당 코드는 다음과 같을 것입니다.
sentence = "the quick brown fox jumps over the lazy dog"
result = {}
for word in sentence.split():
if word in result:
result[word] += 1
else:
result[word] = 1
print(result)
Defaultdict(list)
다음으로, default_dict2.py에서 기본값 []을 갖는 DefaultDict를 생성하고 각 문자에 숫자를 저장해 보겠습니다.
from collections import defaultdict
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count2 = defaultdict(list)
for (key,value) in data:
## Store the number in each letter
word_count2[key].append(value)
print(dict(word_count2))
그런 다음, 터미널에서 스크립트를 실행하십시오.
python default_dict2.py
출력:
{'a': [1, 1, 3], 'b': [1, 2, 3]}
DefaultDict를 사용하지 않았다면, 해당 코드는 다음과 같을 것입니다.
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}
for (key, value) in data:
if key in result:
result[key].append(value)
else:
result[key] = [value]
print(result)
Defaultdict(set)
마지막으로, default_dict3.py에서 기본값 set()을 갖는 DefaultDict를 생성하고 각 문자에 중복되지 않는 숫자를 저장해 보겠습니다.
from collections import defaultdict
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
word_count3 = defaultdict(set)
for (key,value) in data:
## Stores the number that is not repeated in each letter
word_count3[key].add(value)
print(dict(word_count3))
그런 다음, 터미널에서 스크립트를 실행하십시오.
python default_dict3.py
출력:
{'a': {1, 3}, 'b': {1, 2, 3}}
DefaultDict를 사용하지 않았다면, 해당 코드는 다음과 같을 것입니다.
data = [('a', 1), ('a', 1), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]
result = {}
for (key, value) in data:
if key in result:
result[key].add(value)
else:
result[key] = {value}
print(result)
Deque
deque (double-ended queue, 양방향 큐) 는 양쪽 끝에서 빠른 O(1) 추가 및 제거를 지원하는 스택과 큐의 일반화입니다. deque.py에서 deque를 생성하고 몇 가지 연산을 수행해 보겠습니다.
from collections import deque
d = deque([1, 2, 3, 4, 5])
## Append to the right
d.append(6)
print("Append to the right:", d)
## Append to the left
d.appendleft(0)
print("Append to the left:", d)
## Pop from the right
right_element = d.pop()
print("The right element:", right_element)
print("Pop from the right:", d)
## Pop from the left
left_element = d.popleft()
print("The left element:", left_element)
print("Pop from the left:", d)
## Rotate the deque
d.rotate(2)
print("Rotate clockwise the deque:", d)
d.rotate(-2)
print("Rotate counterclockwise the deque:", d)
그런 다음, 터미널에서 스크립트를 실행하십시오.
python deque.py
출력:
Append to the right: deque([1, 2, 3, 4, 5, 6])
Append to the left: deque([0, 1, 2, 3, 4, 5, 6])
The right element: 6
Pop from the right: deque([0, 1, 2, 3, 4, 5])
The left element: 0
Pop from the left: deque([1, 2, 3, 4, 5])
Rotate clockwise the deque: deque([4, 5, 1, 2, 3])
Rotate counterclockwise the deque: deque([1, 2, 3, 4, 5])
요약
이 튜토리얼에서는 namedtuple, Counter, OrderedDict, DefaultDict, 그리고 deque를 포함하여 collections 모듈에서 제공하는 주요 클래스들을 다루었습니다. 이러한 클래스들은 다양한 작업에 유용하며, 여러분의 Python 툴킷에 훌륭한 추가 요소가 될 수 있습니다.



