Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

파이썬의 카운터?

<시간/>

카운터는 동일한 값이 추가되는 횟수를 추적하는 컨테이너입니다. Python 카운터 클래스는 컬렉션 모듈의 일부이며 사전의 하위 클래스입니다.

파이썬 카운터

카운터는 항목이 사전 키로 저장되고 해당 개수가 사전 값으로 저장되는 항목의 정렬되지 않은 컬렉션으로 생각할 수 있습니다.

카운터 항목 수는 양수, 0 또는 음의 정수일 수 있습니다. 키와 값에 대한 제한은 없지만 일반적으로 값은 숫자로 되어 있지만 다른 개체 유형도 저장할 수 있습니다.

초기화 중

카운터는 세 가지 형태의 초기화를 지원합니다. 생성자는 일련의 항목, 키와 개수가 포함된 사전, 또는 문자열 이름을 개수에 매핑하는 키워드 인수를 사용하여 호출할 수 있습니다.

import collections
print (collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))
print (collections.Counter({'a': 2, 'b': 3, 'c':1}))
print(collections.Counter(a=2, b=3, c=1))

세 가지 초기화 형식의 출력은 모두 동일합니다. -

Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

빈 카운터를 만들려면 인수 없이 카운터를 전달하고 업데이트 메서드를 통해 채우세요.

import collections
c = collections.Counter()
print('Initial: ', c)
c.update('abcddcba')
print('Sequence: ', c)
c.update({'a': 1, 'd':5})
print('Dict: ', c)

출력

Initial: Counter()
Sequence: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})
Dict: Counter({'d': 7, 'a': 3, 'b': 2, 'c': 2})

카운트 액세스

카운터가 채워지면 사전 API를 통해 값을 가져올 수 있습니다.

import collections
c = collections.Counter('abcddcba')
for letter in 'abcdef':
   print('%s : %d' %(letter, c[letter]))

출력

a : 2
b : 2
c : 2
d : 2
e : 0
f : 0

Counter는 알 수 없는 항목(위 프로그램에서 언급한 e &f 항목과 같은)에 대해 KeyError를 발생시키지 않습니다. 입력에 값이 표시되지 않으면 해당 개수는 0입니다(위의 출력에서 ​​알 수 없는 항목 e &f의 경우와 같이).

elements() 메서드는 Counter에 알려진 모든 항목을 생성하는 반복자를 반환합니다.

import collections
c = collections.Counter('Python Counters')
c['z'] = 0
print(c)
print(list(c.elements()))

출력

Counter({'t': 2, 'o': 2, 'n': 2, 'P': 1, 'y': 1, 'h': 1, ' ': 1, 'C': 1, 'u': 1, 'e': 1, 'r': 1, 's': 1, 'z': 0})
['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']

요소의 순서는 고정되어 있지 않으며 개수가 0보다 작은 항목은 포함되지 않습니다.

n개의 입력과 각각의 카운트에서 공통 입력을 생성하기 위해 most_common() 함수를 사용합니다.

import collections
c = collections.Counter()
texts = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.'''
for word in texts:
c.update(word.rstrip().lower())
print("Five most common letters in the texts: ")
for letter, count in c.most_common(5):
print("%s: %7d" %(letter, count))

출력

Five most common letters in the texts:
i: 42
e: 38
t: 32
o: 29
u: 29

위의 예는 도수 분포를 생성하기 위해 텍스트(또는 파일을 고려할 수 있음)에 나타나는 문자를 계산한 다음 가장 일반적인 5개를 인쇄합니다. most_common()에 대한 인수를 생략하면 빈도순으로 모든 항목의 목록이 생성됩니다.

산술

카운터 인스턴스는 결과 집계를 위한 산술 및 집합 연산을 지원합니다.

import collections
c1 = collections.Counter(['a', 'b', 'c', 'a' ,'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1: ', c1)
print('C2: ', c2)
print ('\nCombined counts: ')
print(c1 + c2)
print('\nSubtraction: ')
print(c1 - c2)
print('\nIntersection (taking positive minimums): ')
print(c1 & c2)
print('\nUnion (taking maximums): ')
print(c1 | c2)

출력

C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})
Combined counts:
Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
Subtraction:
Counter({'b': 2, 'c': 1})
Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})
Union (taking maximums):
Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

작업을 통해 새 카운터가 생성될 때마다 0 또는 음수 카운트가 있는 항목은 버려집니다.