최대 1 분 소요

리스트의 요소별로 빈도수 카운트 하기

from collections import Counter

items = [10,5,5,8,8,8]
countItems = Counter(items)

print(countItems) # Counter({8: 3, 5: 2, 10: 1})
print(type(countItems)) # <class 'collections.Counter'>

가장 빈도수가 높은 item 가져오기

from collections import Counter

items = [10,5,5,8,8,8]
countItems = Counter(items)

# n=1: 가장 빈도수가 높은 item 하나만 가져오기
print(countItems.most_common(n=1)) # [(8, 3)]
print(countItems.most_common(n=1)[0][0]) # 8
print(countItems.most_common(n=1)[0][1]) # 3

# n=2: 가장 빈도수가 높은 item과 그 다음으로 높은 item 두 개 가져오기
print(countItems.most_common(n=2)) # [(8, 3), (5, 2)]
print(countItems.most_common(n=2)[0][0]) # 8
print(countItems.most_common(n=2)[0][1]) # 3
print(countItems.most_common(n=2)[1][0]) # 5
print(countItems.most_common(n=2)[1][1]) # 2

특정 원소의 빈도수 구하기

from collections import Counter

lst = ['kim', 'kim', 'park', 'choi', 'kim', 'kim', 'kim', 'choi', 'park', 'choi']
print(Counter(lst))
print(Counter(lst)['choi']) # [] 안에 key 값을 넣으면 된다

스크린샷 2023-05-26 오후 4 48 04

from collections import Counter

board = [
  [0, 1, 0, 0, 1],
  [-1, 0, -1, -1, 1],
  [0, 1, 0, -1, 1]
]
for row in board:
  print(Counter(row)[0]) # row에서 0의 개수 카운트

스크린샷 2023-05-26 오후 4 50 07

ref.



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기

태그:

카테고리:

업데이트: