๐Ÿ“‚ Programming/Python

[Python] collections Counter ์‚ฌ์šฉ๋ฒ•

dhyuck 2021. 9. 6. 22:50
๋ฐ˜์‘ํ˜•

collections.Counter

dict์˜ ์„œ๋ธŒ ํด๋ž˜์Šค๋กœ ์š”์†Œ๊ฐ€ ํ‚ค๊ฐ€ ๋˜๊ณ  ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ’์ด ๋˜์–ด ํŽธ๋ฆฌํ•˜๊ฒŒ ๊ฐœ์ˆ˜๋ฅผ ์…€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • ์˜ˆ์ œ 1
import collections

S = "aaabbccdd"
S_counter = collections.Counter(S)

print(S_counter)
for a, b in S_counter.items():
    print(a, b)

'''
์‹คํ–‰ ๊ฒฐ๊ณผ
Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2})
a 3
b 2
c 2
d 2
'''
  • ์˜ˆ์ œ 2
import collections

L = ["zz", "zz", "zz", "aa", "ab", "ab", "ac", "ff", "xx"]
L_counter = collections.Counter(L)

print(L_counter)

for i in L_counter:
    print(i, L_counter[i])

print('L_counter["123"] : %d' %(L_counter["123"]))

'''
์‹คํ–‰ ๊ฒฐ๊ณผ
Counter({'zz': 3, 'ab': 2, 'aa': 1, 'ac': 1, 'ff': 1, 'xx': 1})
zz 3
aa 1
ab 2
ac 1
ff 1
xx 1
L_counter["123"] : 0
'''
๋ฐ˜์‘ํ˜•

'๐Ÿ“‚ Programming > Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Python] datetime ๋ชจ๋“ˆ ์ •๋ฆฌ  (1) 2023.04.21
[Python] ๋ฌธ์ž์—ด ๋‹ค๋ฃจ๊ธฐ  (0) 2021.08.21