๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/Python

[Python] collections.Counter

by rindev 2020. 12. 29.

 

 

docs.python.org/ko/3/library/collections.html?highlight=collection#collections.Counter

 

collections — Container datatypes — Python 3.9.1 ๋ฌธ์„œ

collections — Container datatypes Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple. namedtuple() factory f

docs.python.org

 

์ด๊ฑธ ์•Œ๊ฒŒ๋œ ๊ฑด ๋ฐฑ์ค€ ์ •๋ ฌ > ํ†ต๊ณ„ํ•™ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€....ใ… ใ… 

์ตœ๋นˆ๊ฐ’์„ ๊ตฌํ•˜๋ ค๊ณ  count๋ฅผ ํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ ๋‹ค๋ฅธ์‚ฌ๋žŒ๋“ค์€ ์–ด๋–ป๊ฒŒ ํ’€์—ˆ๋Š”์ง€ ๊ถ๊ธˆํ•ด์„œ ๊ฒ€์ƒ‰ํ•˜๋‹ค๊ฐ€ ์•Œ๊ฒŒ๋๋‹ค!

๊นŒ๋จน๊ธฐ์ „์— ์ •๋ฆฌํ•ด๋‘ฌ์•ผ์ง€..ใ… ใ… 

 

Counter๋ฅผ ์“ฐ๊ธฐ ์œ„ํ•ด์„œ๋Š” from collections import Counter ๋ผ๊ณ  ์ž„ํฌํŠธ๋ฅผ ํ•ด์ค˜์•ผ ํ•œ๋‹ค

๊ทธ๋ฆฌ๊ณ  most_common์„ ํ•ด์ฃผ๋ฉด ๋งŽ์ด ๋“ฑ์žฅํ•œ ๊ฐ’๋ถ€ํ„ฐ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์ค€๋‹ค.

๋“ฑ์žฅ ํšŸ์ˆ˜๊ฐ€ ๊ฐ™์„ ์‹œ ์•ž์˜ ๊ฐ’์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค.

  freqs = Counter(nums).most_common() #nums = [3,3,2,1,4,4,5]
  print(freqs) #[(3, 2), (4, 2), (1, 1), (2, 1), (5, 1)]

 

๋Œ“๊ธ€