dict
, list
, set
및 tuple
에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현Tip!
mutable
은 값이 변한다는 뜻이며immutable
은 값이 변하지 않는다는 의미
# 예시 코드
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)
>>> p[0] + p[1]
33
>>> p
Point(x=11, y=22)
>>> p.x , p.y
(11, 22)
>>> p[x] # error
>>> i, j = p
>>> i
11
>>> j
22
>>> Point
__main__.Point
>>> d = {
... 'x': 100,
... 'y': 200,
... }
>>> p = Point(**d)
>>> p.x
100
>>> p._asdict()
OrderedDict([('x', 100), ('y', 200)])
>>> p._fields
('x', 'y')
>>> re_p = p.replace(x=1000)
>>> re_p
Point(x=1000, y=200)
>>> p
Point(x=100, y=200)
# 예시 코드
>>> from collections import namedtuple
>>> 기술명세 = namedtuple('기술', '기술이름, 자격증, 연차')
>>> 화야 = 기술명세('파이썬', '정보처리기사', '3')
>>> 화야
기술(기술이름='파이썬', 자격증='정보처리기사', 연차='3')
# 예시 코드
>>> from collections import deque
>>> a = [10, 20, 30, 40, 50]
>>> d = deque(a)
>>> d
deque([10, 20, 30, 40, 50])
>>> d.append(100)
>>> d
deque([10, 20, 30, 40, 50, 100])
>>> d.appendleft(1000)
>>> d
deque([1000, 10, 20, 30, 40, 50, 100])
>>> temp = d.pop()
>>> d
deque([1000, 10, 20, 30, 40, 50])
>>> temp
100
>>> temp = d.popleft()
>>> d
deque([10, 20, 30, 40, 50])
>>> temp
1000
>>> d.rotate(2)
>>> d
deque([40, 50, 10, 20, 30])
>>> d.rotate(-1)
>>> d
deque([50, 10, 20, 30, 40])
# 예시 코드
>>> from collections import ChainMap
>>> oneDict = {'one': 1, 'two': 2, 'three': 3}
>>> twoDict = {'four': 4}
>>> chain = ChainMap(oneDict, twoDict)
>>> chain
ChainMap({'one': 1, 'two': 2, 'three': 3}, {'four': 4})
>>> 'one' in chain
True
>>> 'four' in chain
True
>>> 'five' in chain
False
>>> len(chain)
4
>>> chain.values()
ValuesView(ChainMap({'one': 1, 'two': 2, 'three': 3}, {'four': 4}))
>>> chain.keys()
KeysView(ChainMap({'one': 1, 'two': 2, 'three': 3}, {'four': 4}))
>>> chain.items()
ItemsView(ChainMap({'one': 1, 'two': 2, 'three': 3}, {'four': 4}))
>>> chain[0] # error
>>> chain['oneDict'] # error
>>> chain.maps
[{'one': 1, 'two': 2, 'three': 3}, {'four': 4}]
>>> chain.maps[0]
{'one': 1, 'two': 2, 'three': 3}
>>> chain.maps[1]
{'four': 4}
>>> one = [1, 2, 3, 4,]
>>> two = [5, 6, 7, 8]
>>> three = ChainMap(one, two)
>>> three
ChainMap([1, 2, 3, 4,], [5, 6, 7, 8])
>>> 6 in three
True
>>> three.maps[0]
[1, 2, 3, 4]
>>> three.maps[1]
[5, 6, 7, 8]