본문 바로가기

Collections

(4)
[Python] Counter (단어 개수 세기) Counter Sequence Type의 Data element들의 개수를 dict 형태로 반환하는 객체 collections로 부터 import 하여 사용 from collections import Counter 컨테이너에 동일한 값이 몇 개있는지 쉽게 파악할 수 있다. from collections import Counter c = Counter() c = Counter('CocaCola') print(c) Dict type, keyword parameter 등 모두 처리 가능하다. dict를 이용하여 단어들의 개수를 지정하여 원하는 단어를 원하는 개수만큼 가지는 리스트를 생성할 수 있다. from collections import Counter d = {'red' : 4 , 'blue' : 2 } ..
[Python] Collections - defaultdict (단어 개수 세기) defaultdict Dict type의 값에 기본 값을 지정할 수 있는 dictionary 클래스 Dict의 신규 값 생성 시 유용한다. from collections import defaultdict 기존의 Dict d = dict() print(d['first']) 기본 dict를 사용하게 되면 key = 'first'인 item이 없기 때문에 출력하였을 때 에러가 발생한다. defaultdict 사용 from collections import defaultdict d = defaultdict(lambda : 0) #Default 값을 0으로 지정 print(d['first']) 하지만 defaultdict를 이용하여 기본 값을 0으로 지정하고 출력하였을 때 key = 'first'인 아이템을 추가..
[Python] Collections - OrderedDict OrderedDict 기본 딕셔너리와 거의 비슷하지만, 입력된 아이템들의 순서를 기억하는 Dictionary 클래스 즉 Dict와 달리, 데이터를 입력한 순서대로 dict를 반환함 collections로 부터 import 하여 사용 from collections import OrderedDict 기존 Dict 예시 d = {} d['Hello'] = 100 d['How'] = 200 d['are'] = 300 d['you'] = 500 print(d) v = {} v['How'] = 200 v['are'] = 300 v['you'] = 500 v['Hello'] = 100 print(v) if(d == v): print("두 Dictionary가 동일하다") 두 Dictionary의 입력 순서를 다르게 ..
[Python] Collections - deque Python Collections List, Tuple, Dict에 대한 Python Built-in 확장 자료 구조(모듈) 편의성, 실행 효율 등을 사용자에게 제공함 다음과 같은 모듈이 존재한다. from collections import deque from collections import Counter from collections import OrderedDict from collections import defaultdict from collections import namedtuple Deque Stack과 Queue를 지원하는 모듈 List에 비해 효율적인 자료 저장방식을 지원함 collections로 부터 import하여 사용 from collections import deque 기본적으로..