collections.Counter 모듈에 대해서 알아보도록 하겠다.
1. Counter 모듈이란?
파이썬 list 에서 요소별 개수를 알고 싶을 때가 있을 것이다. 주로 중복값이 포함되어 있는 list에서 이러한 정보를 알고 싶은 경우가 많다.
sample = ['a', 'b', 'b', 'c', 'd', 'a']
위와 같은 list에서 'a'는 몇 개인지, 'b'는 몇 개인지에 대한 요소별 개수를 찾아주는 모듈이라고 생각하면 되겠다.
2. Counter 선언법
- 배열을 전달하기
sample = ['a', 'b', 'b', 'c', 'd', 'a']
counter = Counter(sample)
print(counter)
# 실행결과
Counter({'a': 2, 'b': 2, 'c': 1, 'd': 1})
번외이지만 dict 타입보다 Counter가 좋은 점은, counter에 존재하지 않는 요소에 접근을 해도 에러가 나지 않는 것이다.
sample = ['a', 'b', 'b', 'c', 'd', 'a']
counter = Counter(sample)
print(counter['e'])
# 실행결과
0
위의 실행결과 처럼 런타임 에러가 발생하지 않고 0 이라는 결과를 반환하는 것을 확인 할 수 있다.
- 옵션으로 전달하기
counter = Counter(cats=4, dogs=8)
print(counter)
# 실행결과
Counter({'dogs': 8, 'cats': 4})
- dict 전달하기
counter = Counter({'red': 4, 'blue': 2})
print(counter)
# 실행결과
Counter({'red': 4, 'blue': 2})
3. 주요 메소드
- elements() : 요소 펼치기
sample = ['a', 'b', 'c', 'd', 'd', 'd', 'a', 'b', 'd']
counter = Counter(sample)
print(list(counter.elements()))
# 실행결과
['a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd']
요소들을 갯수만큼 나열하여 반환한다. counter.elements() 의 타입은 'itertools.chain'이고 위의 코드에서는 list로 변환한 것이다.
- values() : value 값들만 가져오기
sample = ['a', 'b', 'c', 'd', 'd', 'd', 'a', 'b', 'd']
counter = Counter(sample)
print(counter)
print(counter.values())
# 실행결과
Counter({'d': 4, 'a': 2, 'b': 2, 'c': 1})
dict_values([2, 2, 1, 4])
key가 정렬된 순서대로 value들이 나열되어 반환된다.
- most_common(n) : 상위 n개를 return
sample = ['a', 'b', 'c', 'd', 'd', 'd', 'a', 'b', 'd']
counter = Counter(sample)
print(counter)
print(counter.most_common(2))
# 실행결과
Counter({'d': 4, 'a': 2, 'b': 2, 'c': 1})
[('d', 4), ('a', 2)]
요소 개수가 가장 큰 것부터 정렬되어 상위 n개의 쌍을 return 한다.
- subtract(Counter) : value 값 빼기
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
print(c)
# 실행결과
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
key에 대응되는 value들의 차이를 계산하여 Counter 객체를 반환한다.
**주의할 것
subtract()는 객체의 차가 아닌, value들의 차를 구하는 것임을 명심하자.
객체의 차를 구하려면 아래와 같은 연산을 거치면 된다.
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
print(c - d)
# 실행결과
Counter({'a': 3})
- update([]) : value 더하기
counter = Counter(['a', 'b', 'c', 'd', 'd', 'd', 'a', 'b', 'd'])
print(counter) # update 전
counter.update(['a', 'b'])
print(counter) # update 후
# 실행결과
Counter({'d': 4, 'a': 2, 'b': 2, 'c': 1})
Counter({'d': 4, 'a': 3, 'b': 3, 'c': 1}) # a, b 값 증가
전달한 key들의 개수대로 value값이 증가한 것을 확인 할 수 있다.
출처 : Python3 공식문서
docs.python.org/3/library/collections.html?highlight=counter#collections.Counter
'개발 > 파이썬' 카테고리의 다른 글
[파이썬] 파일 읽기 쓰기, utf-8로 encoding하기 (0) | 2021.02.06 |
---|---|
[파이썬] 싱글톤 객체 만들기 (0) | 2021.01.17 |
이전 댓글