๋”ฅ๋Ÿฌ๋‹/Today I learned :

[๋”ฅ๋Ÿฌ๋‹] collections ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ Counter ํด๋ž˜์Šค

์ฃผ์˜ ๐Ÿฑ 2021. 4. 2. 13:09
728x90
๋ฐ˜์‘ํ˜•

collections ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜  Counter ํด๋ž˜์Šค

 

์นด์šดํ„ฐ ์ฒ˜๋ฆฌ ( ์ˆซ์ž ์„ธ๋Š” ์ฒ˜๋ฆฌ) ํ•จ์ˆ˜ ์ œ๊ณต

 

from collections import Counter

list = ['a','b','c','a','a','c']

 

๋ฐฐ์—ด list์˜ ์š”์†Œ ์ถœํ˜„ ์ˆ˜๋ฅผ ์„ธ์„œ ์ถœ๋ ฅ

์ด ๋•Œ ๊ฒฐ๊ณผ๋Š” ๋”•์…”๋„ˆ๋ฆฌ ์ž๋ฃŒํ˜• (key:value)

counter = counter(list)
print(counter)
Counter({'a' : 3, 'c' : 2, 'b' : 1})

 

์ถœํ˜„ ์ˆœ์„œ๊ฐ€ ๋†’์€ ์ˆœ๋Œ€๋กœ ํ”„๋ฆฐํŠธ

 

most_common์˜ (๋งค๊ฐœ๋ณ€์ˆ˜ n)์„ ์ž…๋ ฅํ•˜๋ฉด ์ƒ์œ„ n ๊ฐœ์˜ ํ‚ค์™€ ๊ฐ’ ๋ฆฌํ„ด

์•„๋ฌด๊ฒƒ๋„ ์ž…๋ ฅํ•˜์ง€ ์•Š์œผ๋ฉด ์ „์ฒด ๋ฆฌํ„ด

 

for elem, cnt in counter.most_common():
	print(elem,cnt)
a 3
c 2
b 1
๋ฐ˜์‘ํ˜•