๋ฅ๋ฌ๋/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
๋ฐ์ํ