python list element count (collections.Counter)

2023. 11. 15. 14:22·python
728x90

list에서 각 요소가 몇개인지 파악하기 위해 사용할 수 있는 collections.Counter에 대해 알아보겠습니다.

 

사용방법은 굉장히 간단합니다.

 

먼저 random을 활용해서 random_list를 만들어 줍니다.

import random
import numpy as np

arr = [random.choice(['A', 'B', 'C']) for _ in range(50)]
print(arr)
np.unique(arr)

 

그 이후 collections에 Counter를 불러와 사용해주면 끝입니다.

from collections import Counter

counter = Counter(arr)
print(counter)

for value, count in counter.items():
    print(f'{value}: {count}개')
    
## Counter({'C': 23, 'A': 15, 'B': 12})

## C: 23개
## A: 15개
## B: 12개

 

Counter의 경우 key,value 형식으로 해당 list 요소의 개수를 파악해 줍니다.

 

이걸 직접 구현해보도록 하겠습니다.

 

def counter_class(word):
    counter = {}
    for item in word:
        if item not in counter:
            counter[item] = 0
        counter[item] += 1
    return counter

counter_class(arr)

## {'C': 23, 'A': 15, 'B': 12}

 

위 코드처럼 먼저 arr를 받아온 뒤 counter = {} 을 만들어준뒤 

for문을 돌며 arr의 요소를 count를 합니다.

저장은 key, value 형식으로 count를 하여 최종 담아주면 끝입니다.

 

감사합니다.

728x90
반응형

'python' 카테고리의 다른 글

[python] BeautifulSoup header 설정 방법  (0) 2024.02.19
python list unique 값 확인 하는 방법  (0) 2023.11.15
python을 활용하여 json 데이터 받아오기 (df 변환)  (0) 2023.08.28
'python' 카테고리의 다른 글
  • [python] BeautifulSoup header 설정 방법
  • python list unique 값 확인 하는 방법
  • python을 활용하여 json 데이터 받아오기 (df 변환)
Balang
Balang
음악 전공생의 개발일지
  • Balang
    Balang
    Balang
  • 전체
    오늘
    어제
  • 반응형
    • All Post (146)
      • python (45)
        • selenium (4)
        • algorithm (9)
        • Django (6)
        • Pandas | Numpy (22)
      • SQL (9)
      • Data Engineer (29)
      • Data Scientist (3)
      • Data Analysis (9)
      • Computer Science (35)
      • Why? (15)
      • 마음가짐 (1)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
Balang
python list element count (collections.Counter)
상단으로

티스토리툴바