ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [파이썬] count, Counter with dictionary
    Python/이것저것 파이썬 2022. 8. 30. 07:31
    반응형

    list.count()

    # list.count() 메서드를 이용.
    some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    duplicates = set()
    for each in set(some_list):
        if some_list.count(each) > 1:
            duplicates.add(each)
    print(duplicates)
    # 컴프리헨션으로 정리
    duplicates = set(each for each in set(some_list) if some_list.count(each) > 1)
    print(duplicates)

     

    dictionary

    # 딕셔너리를 이용.
    some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    counter = {}
    for each in some_list:
        counter.setdefault(each, 0)
        counter[each] += 1
    duplicates = set()
    for key, value in counter.items():
        if value > 1:
            duplicates.add(key)
    print(duplicates)

     

    조금 더 단순하게... 

    some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    
    counter = {}
    duplicates = set()
    
    for each in some_list:
        counter.setdefault(each, 0)
        counter[each] += 1
        if counter[each] > 1:
            duplicates.add(each)
    
    print(duplicates)

     

    collections.Counter()

    # collections 패키지의 Counter와 컴프리헨션으로 정리.
    
    from collections import Counter
    
    
    some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
    counter = Counter(some_list)
    duplicates = set(k for k, v in Counter(some_list).items() if v > 1)
    print(duplicates)
    반응형
Designed by Tistory.