์ƒˆ์†Œ์‹

๐Ÿ ํŒŒ์ด์ฌ (Python)

ํŒŒ์ด์ฌ(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)]

 

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.