1. collections
python.flowdas.com/library/collections.html
collections --- 컨테이너 데이터형 — 파이썬 설명서 주석판
collections --- 컨테이너 데이터형 소스 코드: Lib/collections/__init__.py 이 모듈은 파이썬의 범용 내장 컨테이너 dict, list, set 및 tuple에 대한 대안을 제공하는 특수 컨테이너 데이터형을 구현합니다. named
python.flowdas.com
collections 라이브러리에서 평소에 deque를 자주 쓴다. 가끔씩 Counter을 쓰는 경우도 있다.
1. collections.deque
import collections list_array = [1,2,3] stack = collections.deque(list_array) # deque([1, 2, 3]) stack.appendleft(-1) # deque([-1, 1, 2, 3]) # 좌측에 값을 추가한다. stack.append(10) # deque([-1, 1, 2, 3, 10]) # 우측에 값을 추가한다. stack.pop() # deque([-1, 1, 2, 3]) # 끝의 값을 반환하고, 삭제한다. stack.popleft() # deque([1,2,3]) # 제일 첫번째 값을 반환하고, 삭제한다. extends_right = [10,20,30] extends_left = [1,2,3] stack.extend(extends_right) # deque([1, 2, 3, 10, 20, 30]) # iterable한 객체를 우측에 추가한다. stack.extendleft(extends_left) # deque([3, 2, 1, 1, 2, 3, 10, 20, 30]) # iterable한 객체를 좌측에 추가한다. 요소가 뒤집어지니 조심 print(stack.index(1)) # 2 # index(x) x의 처음위치를 반환한다. print(stack.index(1,3,5)) # 3 # index(x,start,end) x의 state와 end 사이의 위치에서 탐색한다. try: print(stack.index(1,4,5)) except: print('ValueError 1 is not in deque') # ValueError: 1 is not in deque # Value Error가 뜬다. stack.rotate(1) # deque([30, 3, 2, 1, 1, 2, 3, 10, 20]) # 우측으로 x칸씩 이동한다. # 음수도 가능 음수는 반대방향으로 돈다. stack.insert(1,100) # deque([30, 100, 3, 2, 1, 1, 2, 3, 10, 20]) # stack.insert(ind,val) # 해당 ind에 val을 삽입한다. print(stack.count(1)) # 2 # x의 개수를 세준다. stack.remove(2) # deque([30, 100, 3, 1, 1, 2, 3, 10, 20]) # 해당 val의 첫번째 위치에 존재하는걸 삭제해준다. stack.clear() # deque([]) # stack을 전부 비운다.
2. collections.Counter
from collections import Counter so = Counter('ababbbbcccc') co = Counter({'red':4,'blue':5}) newco = Counter(cats=4,dogs=5) print(newco) # Counter({'dogs': 5, 'cats': 4}) print(so) # Counter({'b': 5, 'c': 4, 'a': 2}) print(co) # Counter({'blue': 5, 'red': 4}) for val in so.elements(): print(val) # 요소를 개수만큼 반환해줍니다. 뒤에서부터 반복됩니다. print(so.most_common()) # [('b', 5), ('c', 4), ('a', 2)] # 자주 쓰이는거 가장 많이 출연된 순서대로 출력해줍니다. print(so.most_common(1)) # [('b', 5)] # 만약 most_common(n) n을 입력시, 가장 흔한순서대로 n개만큼 출력합니다. sum_so = Counter({'a':10,'b':20,'c':30,'d':5}) so.update(sum_so) print(so) # Counter({'c': 34, 'b': 25, 'a': 12, 'd': 5}) # 일반적인 dictionary에서 교환하는것과 달리 여기는 더해준다. sub_so = Counter(a=10,b=20,c=30,e=30) so.subtract(sub_so) # Counter({'b': 5, 'd': 5, 'c': 4, 'a': 2, 'e': -30}) # substract는 update와 달리 빼주는 역할을 한다. a = Counter(a=5,b=5) b = Counter(a=5,b=6,c=5) print(a+b) # Counter({'b': 11, 'a': 10, 'c': 5}) # 두개를 더해줍니다. print(a-b) # Counter() # 두개를 빼주는 대신 양의 정수만 유지해줍니다. print(a|b) # Counter({'b': 6, 'a': 5, 'c': 5}) # 두 딕셔너리의 합집합입니다. # max(a[x],b[x]) print(a&b) # Counter({'a': 5, 'b': 5}) # 두 딕셔너리의 교집합입니다. # min(a[x],b[x])
이 Counter객체는 자주 쓰는 편은 아니지만 개수를 셀때는 압도적으로 편리하기 때문에 가끔씩 쓰는 객체이다.
2. heapq
3. bisect
4. itertools
5. functools