Python
2014.04.30 10:04

collections.counter() 함수

조회 수 14098 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print

https://docs.python.org/2.7/library/collections.html?highlight=collections.counter#collections.Counter


Counter는 해쉬가 가능한 객체를 위한 dict의 서브 클래스이다. Counter는 요소들이 사전의 키로서 저장되는 순서를 가지지 않는 컬렉션이고 그것들의 개수는 사전의 값으로 저장된다. 0 또는 음수를 포함한 어떠한 정수 값도 카운트 될 수 있다. Counter 클래스는 다른 언어의 bag이나 멀티셋과 비슷하다.

요소들 Elements 은 iterable 또는 또 다른 mapping(또는 counter)로 부터 생성되어 카운트 된다:

>>>
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

카운터 객체는 KeyError를 발생시키는 대신 나오는 0 카운트의를 리턴하는 사전 인터페이스를 가진다.

>>>
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0

카운트를 0으로 설정하는 것은 요소를 삭제 하지 못한다. 삭제를 위해 del 을 사용할 것:

>>>
>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry

2.7 버전에서 새로 추가됨.


카운터 객체는 모든 사전에 대해 사용 가능한 3가지 메소드를 지원한다:

elements()

각 요소를 카운트 만큼 반복해 주는 나열자를 반환한다. 요소들은 순서없이 반환된다. 만약 요소의 카운트가 1보다 작다면 element()는 그 요소를 무시한다.

>>>
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
most_common([n])

n개의 가장 많이 나오는 요소와 카운트의 리스트를 반환한다. 만약 n이 지정되지 않으면, most_common()은 counter 상의 모든 요소를 반환한다. 개수가 많은 순서로 나오는데 같은 개수는 순서없이 나열 된다:

>>>
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
subtract([iterable-or-mapping])

나열자 또는 다른 mapping(또는 counter)로 부터 요소들의 개수를 뺀다. dict.update()와 비슷하지만 대체하는 것이 아니라 개수를 빼는 것. 입력과 출력 둘다 0 또는 음수를 가질 수 있다.

>>>
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

counter에서 다른 역할을 하는 2개의 메소드를 제외하고 보통의 사전에서 사용하는 메소드들은 모두 사용할 수 있다.

fromkeys(iterable)

이 클래스 메소드는 Counter 객체에는 적용되지 않는다.

update([iterable-or-mapping])

요소들이 다른 나열자나 mapping(또는 counter)로부터 추가된다. dict.update()와 비슷하지만, 요소들을 대치하는 대신에 개수를 더한다. 또한, 나열자는 요소들의 시퀀스로 이루어 져야 하며, (key, value)의 시퀀스틑 적용되지 않는다.


Counter 객체로 작업하는 일반적인 패턴들:

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
c += Counter()                  # remove zero and negative counts

몇몇 수학 연산들은 멀티셋을 생성하기 위한 Counter 객체의 조합으로 제공될 수 있다(0 보다 큰 카운트를 가져야 함). 상응하는 요소의 개수를 더하거나 빼기 위해 카운터의 덧셈 뺄셈을 사용할 수 있다. 교집합과 합집합은 상응하는 요소의 최소값과 최대값을 반환한다. 각 연산의 입력은 부호를 가질수 있지만, 출력은 0 이하의 값을 가지는 요소는 배제한다.

>>>
>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

Note

 

Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.

  • The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.
  • The most_common() method requires only that the values be orderable.
  • For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() andsubtract() which allow negative and zero values for both inputs and outputs.
  • The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
  • The elements() method requires integer counts. It ignores zero and negative counts.

Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
20 Python python 내장 함수 2014.04.30 16065 0
19 Python zip() 함수 2014.04.30 22330 0
18 Python 유용한 Python 함수 및 기능들 2014.04.30 11713 0
» Python collections.counter() 함수 2014.04.30 14098 0
16 Python filter()와 reduce() 함수 2014.04.30 10987 0
15 Python Python 유용한 코드 모음 2014.05.20 15131 0
14 Python C, Python and swig on Windows with Visual Studio 2014.05.29 11528 0
13 Python [Sconscript] Install method 2014.05.29 8519 0
12 Python 커맨드 라인에서 컬러로 출력하기 termcolor 2014.06.27 10596 0
11 Python pyBest 소스 secret 2016.01.20 0 0
10 Python pygoogle 파이썬으로 구글 검색결과 가져오기 library 2016.01.20 9857 0
9 Python json 데이터 핸들링 2017.03.09 8618 0
8 Python [tensorflow] 선형회귀 예제 2018.02.05 5384 0
7 Python [tensorflow] 텐서플로우 문서 한글번역본 2018.03.22 5143 0
6 Python matplot에서 한글이 보이도록 하는 코드 2019.03.06 6019 0
목록
Board Pagination ‹ Prev 1 2 3 Next ›
/ 3

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5