๐Counter
์์ดํ ์ ๋ํ ๊ฐ์๋ฅผ ๊ณ์ฐํด ๋์ ๋๋ฆฌ๋ก ๋ฆฌํดํ๋ ๊ฐ์ฒด
from collections import Counter
nums = [1, 1, 2, 3, 4, 4]
counter = Counter(nums) # Counter({1: 2, 4: 2, 2: 1, 3: 1})- ์๋ ๊ฐ์ ์ ๊ทผํด๋ ์๋ฌ๊ฐ ๋ฐ์ํ์ง ์๊ณ 0์ return
- Counter ๊ฐ์ฒด๋ ๋์ ๋๋ฆฌ๋ก ๋ฆฌํดํ๋ฏ๋ก ๋์ ๋๋ฆฌ์ฒ๋ผ ์ธ ์ ์์
Example
- counter[key] : key๋ก ๊ฐ ์ฐพ๊ธฐ
- counter[key] += v : key์ ํด๋นํ๋ v ์ถ๊ฐํ๊ฑฐ๋ ๋ฐ๊พธ๊ธฐ
- key in counter :
inํค์๋ ์ฌ์ฉํด key๊ฐ Counter์ ์กด์ฌํ๋์ง ํ์ธํ๊ธฐ
๐Counter ํจ์
๐most_common(n)
๊ฐ์ฅ ๋น๋ ์๊ฐ ๋์ ์์๋ฅผ ์ถ์ถํ๋ ํจ์
from collections import Counter
nums = [1, 1, 2]
counter = Counter(nums)
counter.most_common(1) # [(1, 2)]- n์ ์๋ตํ ์ ๋ชจ๋ ์์ return
- ๋ฆฌ์คํธ ์์ ํํ ํ์
[(v1, cnt1), (v2, cnt2)]์ผ๋ก returnํจ
๐elements()
์นด์ดํธ ๋ ์ซ์๋งํผ์ ์์๋ฅผ returnํด์ฃผ๋ ํจ์
from collections import Counter
nums = [1, 1, 2]
counter = Counter(nums)
result = list(counter.elements()) # [1, 1, 2]- ํจ์๋ฅผ ์ฌ์ฉ ํ list๋ก typecastํด์ ์ฌ์ฉ (๊ทธ๋ฅ Counter ๊ฐ์ฒด๋ฅผ list๋ก typecastํ๋ฉด cnt>1์ธ ์์๋ ํ๋๋ง ๋ธ)
๐subtract()
์์๋ฅผ ๋นผ์ฃผ๋ ํจ์
from collections import Counter
list1, list2 = [1, 2, 3], [1, 1, 2]
counter1, counter2 = Counter(list1), Counter(list2)
counter1.subtract(counter2) # Counter({3: 1, 2: 0, 1: -1})- counter1์์ counter2์ element๋ฅผ ๋บ ๊ฒ์ด counter1
- ํด๋น ํจ์๋ฅผ ์ํํ ๊ฒฐ๊ณผ๊ฐ ์์๋ผ๋ฉด ์์ ๊ฐ ๋ฐํ (์ฐ์ฐ์์ ์ ์ธ๋์ง ์์)
๐์ฐ์ ์ฐ์ฐ
๐๋ง์ ์ฐ์ฐ
from collections import Counter
list1, list2 = [1, 2, 3], [1, 1, 2]
counter1, counter2 = Counter(list1), Counter(list2)
counter1 + counter2 # Counter({1: 3, 2: 2, 3: 1})๐๋บ์ ์ฐ์ฐ
from collections import Counter
list1, list2 = [1, 1, 3], [1, 3, 4]
counter1, counter2 = Counter(list1), Counter(list2)
counter1 - counter2 # Counter({1: 1})- ๊ฒฐ๊ณผ๊ฐ์ด ์์๊ฐ ์๋๋ผ๋ฉด ์ถ๋ ฅํ์ง ์์ (
0,์์)
๐์งํฉ ์ฐ์ฐ
๐Counter1 | Counter2
ํฉ์งํฉ์ ๊ตฌํ๋ ์ฐ์ฐ
from collections import Counter
list1, list2 = [1, 2, 3], [1, 1, 2]
counter1, counter2 = Counter(list1), Counter(list2)
counter1 | counter2 # Counter({1: 2, 2: 1, 3: 1})๐Counter1 & Counter2
๊ต์งํฉ์ ๊ตฌํ๋ ์ฐ์ฐ
from collections import Counter
list1, list2 = [1, 2, 3], [1, 1, 2]
counter1, counter2 = Counter(list1), Counter(list2)
counter1 & counter2 # Counter({1: 1, 2: 1})