Counter

 

Counter는 collections의 모듈인 Counter 클래스를 사용합니다.

 

Counter는 항목의 개수를 세어줄 때 유용하게 사용할 수 있습니다.

 

from collections import Counter

a=[1,2,3,4,5,1,3,5,1,5,5]
b='abcdeaceabaeaa'

# 출력>>Counter({5: 4, 1: 3, 3: 2, 2: 1, 4: 1})
print(Counter(a))

# 출력>>Counter({'a': 6, 'e': 3, 'b': 2, 'c': 2, 'd': 1})
print(Counter(b))

Counter는 딕셔너리 형태로 Key 값으로 요소의 이름, Value 값으로 요소들의 횟수를 출력해줍니다.

 

from collections import Counter

b='abcdeaceabaeaa'
c='eabdeabc'

# 출력>>Counter({'a': 6, 'e': 3, 'b': 2, 'c': 2, 'd': 1})
print(Counter(b))

# 출력>>Counter({'e': 2, 'a': 2, 'b': 2, 'd': 1, 'c': 1})
print(Counter(c))

# 출력>>Counter({'a': 8, 'e': 5, 'b': 4, 'c': 3, 'd': 2})
print(Counter(b) + Counter(c))

# 출력>>Counter({'a': 4, 'c': 1, 'e': 1})
print(Counter(b) - Counter(c))

# 출력>>Counter()
print(Counter(c) - Counter(b))

# 출력>>[('a', 6), ('e', 3)]
print(Counter(b).most_common(2))

Counter를 이용해 계산도 가능합니다.

 

c에서 b를 빼면 c가 전체적으로 더 작기 때문에 빈 값으로 나옵니다.

 

most_common('상위요소 수')를 통해 상위요소를 출력할 수 있습니다.
상위요소의 수를 쓰지 않으면 전체요소를 출력해줍니다.

 


count와 Counter는 모두 항목의 개수를 세어줄 때 많이 사용합니다.

 

count의 시간 복잡도는 O(N)입니다.
여기서 각각의 리스트의 개수를 확인하기 위해서는 for문을 통해 count를 n번하기 때문에 시간 복잡도는 O(N2)입니다.

 

Counter 클래스를 이용해 Counter를 n번 하면 시간 복잡도는 O(N)입니다.
딕셔너리에서 원소를 접근할 때의 시간 복잡도는 O(1)이기 때문입니다.

 

from collections import Counter

a=[0, 1, 2, 3, 4, 0, 2, 4, 0, 2, 1, 1, 1, 1, 1, 2, 4]

# count 사용
for i in range(5):
    # 출력>>3 6 4 1 3
    print(a.count(i),end=' ')

# Counter 사용
counter = Counter(a)
for i in range(5):
    # 출력>>3 6 4 1 3
    print(counter[i],end=' ')

count를 여러번 사용하는 경우는 Counter 클래스가 더욱 유용합니다.

'Python > 파이썬 기초' 카테고리의 다른 글

파이썬_기초 33_zip  (0) 2020.06.04
파이썬_기초 32_enumerate  (0) 2020.05.31
파이썬_기초 30_딕셔너리(Dictionary)  (0) 2020.05.30
파이썬_기초 29_lambda  (0) 2020.05.19
파이썬_기초 28_def 함수이름()  (0) 2020.05.19

+ Recent posts