hgk0404
hgk0404.tistory
hgk0404

공지사항

전체 방문자
오늘
어제
  • 전체 카테고리
    • [컴퓨터비전]
    • [Computer Science]
      • [컴퓨터네트워크]
      • [알고리즘]
      • [자료구조 in C]
      • [C & C++]
      • [이산수학]
      • [Math]
    • [머신러닝]
      • [Numpy, Pandas]
    • [Cloud]
      • [AWS]
      • [NCP]
      • [Kubernetes]
      • [Terraform]
    • [Dev]
      • [가상환경]
      • [Linux]
      • [Docker]
    • [Python]
    • [Coding Test]
      • [백준]
      • [프로그래머스]
      • [SQL]
    • [WEB]
    • [자격증, 일상]
    • [엑셀]
    • [금융]

인기 글

최근 글

최근 댓글

250x250
hELLO · Designed By 정상우.
hgk0404

hgk0404.tistory

[Python]

[Python] Counter 모듈 사용법

2022. 7. 5. 05:47
728x90

데이터의 개수를 셀때 사용하는 Counter 모듈에 대해 알아보도록 하겠습니다.

 

Counter 모듈은 collections에 있어서 다음 코드를 입력해야 합니다.

from collections import Counter

 

Counter 모듈은 dict()의 기능을 그대로 구현해 줍니다. hash처럼이요.

데이터의 개수를 세어 dict()처럼 key와 value로 구분해 주는 most_common() 함수가 있습니다.

 

from collections import Counter

print(Counter('SamSung').most_common())

 

결과)

[('S', 1), ('a', 1), ('m', 1), ('s', 1), ('u', 1), ('n', 1), ('g', 1)]

대문자 먼저 정렬해주고 그 이후로는 알파벳 순서대로 개수와 함께 출력이 됩니다.

 

from collections import Counter

fruits = [ 'Apple', 'Banana', 'Apple', 'Orange', 'lemon', 'Apple', 'lemon' ]
print(Counter(fruits))

 

결과)

Counter({'Apple': 3, 'lemon': 2, 'Banana': 1, 'Orange': 1})

 

상위요소 n개 출력

from collections import Counter

fruits = [ 'Apple', 'Banana', 'Apple', 'Orange', 'lemon', 'Apple', 'lemon' ]
print(Counter(fruits).most_common(2))

 

결과)

[('Apple', 3), ('lemon', 2)]

 

most_common() 함수에 매개값으로 2를 넣었더니 상위 값 2개까지만 출력되었습니다.

728x90
저작자표시 동일조건 (새창열림)

'[Python]' 카테고리의 다른 글

[Python] 파이썬 max, min 함수 - max(map(max, graph))  (0) 2022.07.06
[Python] 파이썬 ord함수, chr함수 차이점  (0) 2022.07.06
[Python] 파이썬 for-else  (0) 2022.07.05
[Python] 파이썬 리스트 슬라이싱 - (슬라이싱 추가예정)  (0) 2022.07.03
[Python] 파이썬 sort(), sorted() 함수 사용법  (0) 2022.07.03
'[Python]' 카테고리의 다른 글
  • [Python] 파이썬 max, min 함수 - max(map(max, graph))
  • [Python] 파이썬 ord함수, chr함수 차이점
  • [Python] 파이썬 for-else
  • [Python] 파이썬 리스트 슬라이싱 - (슬라이싱 추가예정)
hgk0404
hgk0404
공부기록

티스토리툴바