νμ΄μ¬(Python) Collections λͺ¨λ - counter , most_common
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)]