๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

[python]Counter ๊ด€๋ จ ๋ฉ”์†Œ๋“œ

by mingzoo 2022. 12. 12.

1. collections.Counter().elements()

c = Counter(a=4, b=2, c=0, d=-2)
print(c.elements())

>>>['a', 'a', 'a', 'a', 'b', 'b']

 

2. collections.Counter().most_common(n)

์ธ์ž๋กœ ๋“ค์–ด๊ฐ€๋Š” n์€ ์ถœ๋ ฅํ•˜๊ณ ์ž ํ•˜๋Š” ์›์†Œ์˜ ๊ฐœ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ์•„๋ž˜์—์„œ๋Š” 3์„ ์ž…๋ ฅํ•˜์—ฌ ๊ฐ€์žฅ ๋งŽ์ด ์–ธ๊ธ‰๋œ ์›์†Œ 3๊ฐœ์— ๋Œ€ํ•œ ์นด์šดํŒ… ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ–ˆ๋‹ค. 

Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

 

3. collections.Counter().subtract(๋‹ค๋ฅธ counter)

์„œ๋กœ ๋‹ค๋ฅธ ๋‘๊ฐœ์˜ Counter์˜ ๊ฐ’์„ ๋นผ๋Š” ํ˜•ํƒœ์ด๋‹ค.

c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
728x90