UOMOP
collections 모듈(module) 본문
- List, Tuple, Dict에 대한 Python Built-in 확장 자료 구조
- 아래의 모듈이 존재
- from collections import deque
- from collections import Counter
- from collections import defaultdict
- from collections import namedtuple
1. deque
from collections import deque
d = deque([2, 3, 4, 5])
print(d)
d.append(6)
print(d)
d.appendleft(1)
print(d)
d.pop()
print(d)
deque([2, 3, 4, 5])
deque([2, 3, 4, 5, 6])
deque([1, 2, 3, 4, 5, 6])
deque([1, 2, 3, 4, 5])
d.rotate(1)
print(d)
d.rotate(2)
print(d)
d.rotate(2)
print(d)
deque([5, 1, 2, 3, 4])
deque([3, 4, 5, 1, 2])
deque([1, 2, 3, 4, 5])
d.extend([6, 7, 8])
print(d)
d.extendleft([2, 3, 4])
print(d)
deque([1, 2, 3, 4, 5, 6, 7, 8])
deque([4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8])
2. Counter
from collections import Counter
SorB = ["S", "S", "B", "S", "B", "B", "B"]
c = Counter(SorB)
print(c)
Counter({'B': 4, 'S': 3})
A = {"red" : 4, "blue" : 2, "yellow" : 3}
B = {"blue" : 6, "red" : 1, "green" : 9}
C = Counter(A) + Counter(B)
print(C)
print(list(C.elements()))
Counter({'green': 9, 'blue': 8, 'red': 5, 'yellow': 3})
['red', 'red', 'red', 'red', 'red', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green', 'green']
a = Counter(a = 4, b = 2, c = 3)
b = Counter(b = 3, a = 1, d = 4)
print(a + b)
print(a & b)
print(a | b)
a.subtract(b)
print(a)
Counter({'a': 5, 'b': 5, 'd': 4, 'c': 3})
Counter({'b': 2, 'a': 1})
Counter({'a': 4, 'd': 4, 'b': 3, 'c': 3})
Counter({'a': 3, 'c': 3, 'b': -1, 'd': -4})
3. namedtuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(x = 11, y = 22)
print(p[0] + p[1])
print(p.x + p.y)
print(Point(x = 11, y = 22))
33
33
Point(x=11, y=22)
'Summary > Python' 카테고리의 다른 글
List, Tuple, Set, Dict (0) | 2022.01.15 |
---|
Comments