🐍 파이썬 (Python)

파이썬(Python) Collections λͺ¨λ“ˆ - counter , most_common

Newmon 2020. 3. 10. 21:18

collections λͺ¨λ“ˆμ€ 기본적으둜 νŒŒμ΄μ¬μ— λ‚΄μž₯λ˜μ–΄μžˆλŠ” λ‚΄μž₯ν•¨μˆ˜μž…λ‹ˆλ‹€. (λ”°λ‘œ μ„€μΉ˜κ°€ ν•„μš” μ—†..)

λ¦¬μŠ€νŠΈλ‚˜, λ¬Έμžμ—΄μ˜ μš”μ†Œμ— λŒ€ν•œ 개수λ₯Ό κ΅¬ν• λ•Œ λ°˜λ³΅λ¬ΈμœΌλ‘œλ„ ꡬ할 수 μžˆμ§€λ§Œ, counter ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•˜λ©΄ νŽΈλ¦¬ν•©λ‹ˆλ‹€.

그리고 κ°€μž₯ λ†’μ€λΉˆλ„(frequency)둜 λ“±μž₯λ˜λŠ” κ°’ (μ΅œλΉˆκ°’)을 κ΅¬ν•˜λŠ” most_commonν•¨μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€.

 

 

 

counter ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄ 리슀트의 κ°œμˆ˜μ„ΈκΈ°

collections.Counter(a) : aμ—μ„œ μš”μ†Œλ“€μ˜ 개수λ₯Ό μ„Έμ–΄, λ”•μ…”λ„ˆλ¦¬ ν˜•νƒœλ‘œ λ°˜ν™˜ν•©λ‹ˆλ‹€.  {문자 : 개수} ν˜•νƒœ

*예제 μ½”λ“œ

import collections

b = [1,3,4,2,3,5,2,3,9]
a = [1,2,3,4,1,5,3,1,3,4,2,3]
print(collections.Counter(a) , collections.Counter(b))

*좜λ ₯ κ²°κ³Ό

>>>
Counter({3: 4, 1: 3, 2: 2, 4: 2, 5: 1}) Counter({3: 3, 2: 2, 1: 1, 4: 1, 5: 1, 9: 1})

 

 

 

 

counter  - μ—°μ‚°

counter ν•¨μˆ˜λ‘œ κ΅¬ν•œ λ”•μ…”λ„ˆλ¦¬μ˜ κ°’(value)끼리 연산이 λœλ‹€. 연산은 + , - , &(ꡐ집합), |(ν•©μ§‘ν•©) λ„€κ°€μ§€κ°€ κ°€λŠ₯ν•©λ‹ˆλ‹€.

*예제 μ½”λ“œ

import collections

b = [1,1,1,1,1,1]
a = [1,1,2,2,2,2]

print(collections.Counter(a) - collections.Counter(b))
print(collections.Counter(a) + collections.Counter(b))

*좜λ ₯ κ²°κ³Ό

>>>
Counter({2: 4})
Counter({1: 8, 2: 4})

 

 

 

 

most_common() ν•¨μˆ˜ - μ΅œλΉˆκ°’ κ΅¬ν•˜κΈ°

collections.Counter(a).most_common(n)   : a의 μš”μ†Œλ₯Ό μ„Έμ–΄, μ΅œλΉˆκ°’ n개λ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€. (λ¦¬μŠ€νŠΈμ— λ‹΄κΈ΄ νŠœν”Œν˜•νƒœλ‘œ)

 

*예제 μ½”λ“œ

import collections
a  = [1,1,1,2,3,2,3,245,9]

print(collections.Counter(a).most_common(3))

 

*좜λ ₯ κ²°κ³Ό

>>>
[(1, 3), (2, 2), (3, 2)]