목차

    python

    파이썬 collections 모듈 Counter 사용법

    고로케 2021. 6. 20.

    목차

      반응형
      • Counter() : 문자열이나, list 의 요소를 카운팅하여 많은 순으로 딕셔너리형태로 리턴한다
      from collections import Counter
      
      a_list = ['a','s','d','s']
      Counter(a_list)
      => {'s':2,'a':a,'d':1}

       

      • most_common() : 개수가 많은 순으로 정렬된 튜플 배열 리스트를 리턴한다
      from collections import Counter
      
      a_list = ['a','s','d','s']
      Counter(a_list).most_common()
      => [('s', 2), ('a', 1), ('d', 1)]
      
      # 몇개 보여줄지 숫자를 넣어 조절
      Counter(a_list).most_common(2)
      => [('s', 2), ('a', 1)]

       

      • 활용법

      sorted(a_list) 먼저 사용하고 -> Counter() 사용

      from collections import Counter
      
      a_list = ['a','s','d','d','s']
      # 리스트 순서대로 먼저 많은 것 순서
      Counter(a_list).most_common()
      => [('s', 2), ('d', 2), ('a', 1)]
      
      b_list = sorted(a_list)
      => ['a', 'd', 'd', 's', 's']
      # 알파벳 순
      Counter(b_list).most_common()
      => [('d', 2), ('s', 2), ('a', 1)]

       

      • sorted( a_list , key=labda x:x) 함수식을 이용하여 정렬
      a_list = ['a', 's', 'd', 'd', 's', 'x']
      
      # 숫자 역순(내림차순), 문자 역순(아스키 값 이용)
      a_counter = Counter(a_list).most_common()
      print(sorted(a_counter, key=lambda x: (-x[1], -ord(x[0]))))
      
      => [('s', 2), ('d', 2), ('x', 1), ('a', 1)]

       

       

       

       

       

      파이썬 collections 모듈 Counter 사용법

      반응형

      댓글