산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

파이썬 collections.Counter: 효율적 카운팅, 업데이트, 산술 연산

파이썬 collections.Counter: 효율적 카운팅, 업데이트, 산술 연산

파이썬 Counter란?

파이썬의 Counter는 이터러블에서 각 요소의 출현 횟수를 세는 특수 컨테이너입니다. dict를 상속받아 요소를 키로, 개수를 값으로 저장하므로 해시 테이블 스타일 카운팅에 이상적입니다.

왜 Counter를 사용하는가?

Counter 시작하기

collections에서 클래스 임포트:

from collections import Counter

이제 아무 이터러블이나 Counter에 전달해 개수 매핑 얻기.

예제 – 리스트 카운팅

list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

출력: Counter({'x': 4, 'y': 2, 'z': 2})

예제 – 문자열 카운팅

my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))

출력: Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

예제 – 딕셔너리 카운팅

dict1 = {'x': 4, 'y': 2, 'z': 2}
print(Counter(dict1))

출력: Counter({'x': 4, 'y': 2, 'z': 2})

예제 – 튜플 카운팅

tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))

출력: Counter({'x': 4, 'y': 2, 'z': 2})

Counter 초기화, 업데이트, 접근

초기화

print(Counter("Welcome to Guru99 Tutorials!"))  # 문자열
print(Counter(['x','y','z','x','x','x','y','z']))  # 리스트
print(Counter({'x': 4, 'y': 2, 'z': 2}))  # 딕셔너리
print(Counter(('x','y','z','x','x','x','y','z')))  # 튜플
# 빈 카운터
_count = Counter()

업데이트

_count.update('Welcome to Guru99 Tutorials!')
print(_count)

출력: Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})

개수 접근

print('%s : %d' % ('u', _count['u']))
for char in 'Guru':
    print('%s : %d' % (char, _count[char]))

출력: u : 3 / G : 1 / u : 3 / r : 2 / u : 3

요소 삭제

del _count['x']
print(_count)

출력: Counter({'y': 2, 'z': 2})

산술 연산

Counter는 집합형 산술 지원. 양수 개수만 보존; 결과에서 음수 값은 버려짐.

counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z': 4})

# 덧셈
print(counter1 + counter2)
# 뺄셈
print(counter1 - counter2)
# 교집합
print(counter1 & counter2)
# 합집합
print(counter1 | counter2)

출력:

Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})

주요 메서드

elements() 사용

counter = Counter({'x': 5, 'y': 2, 'z': -2, 'x1': 0})
for e in counter.elements():
    print(e)

출력: x x x x x y y

most_common() 사용

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter.most_common(2))
print(counter.most_common())

출력: [('y', 12), ('x', 5)] / [('y', 12), ('x', 5), ('x1', 0), ('z', -2)]

subtract() 사용

c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.subtract(c2)
print(c1)

출력: Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})

update() 사용

c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.update(c2)
print(c1)

출력: Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

개수 재할당

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
counter['y'] = 20
print(counter)

출력: Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})

요소 개수 가져오기 및 설정

counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter['y'])
counter['y'] = 20
counter['y1'] = 10
print(counter)

출력: 12 / Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})

요약

python

  1. Python strip() 메서드 완전 정복: 종합 가이드와 실전 예제
  2. Python str.count() 마스터하기: 문자 및 부분문자열 개수 세기 예제
  3. Python format() 문자열 마스터하기: 명확한 예제로 완전 정복
  4. Python len() 함수: 객체 길이 측정 실전 가이드
  5. Python String.find() 메서드 마스터하기: 문법, 예제, 대안 비교
  6. 파이썬 람다 함수 마스터하기: 실용 예제 & 모범 사례
  7. 파이썬 round() 함수 완전 정복: 실용 예제로 이해하기
  8. 파이썬 map() 함수 마스터하기: 문법, 예제, 모범 사례
  9. 파이썬 timeit()으로 실행 시간 측정하기: 실용 예제
  10. 파이썬 list.count() 전문가 가이드: 실전 예제로 배우는 요소 개수 세기