티스토리 뷰
collection 라이브러리의 Counter()에 대해 간략하게 알아보도록 하겠습니다.
Counter은 반복이 가능한 객체가 있을 때 객체 안에 동일한 값이 몇 개 있는 지를 알려주는 함수입니다.
먼저 Counter 클래스를 사용하기 위해 아래와 같이 import 해줍니다.
from collections import Counter
1. 리스트 안에 있는 동일한 알파벳을 count 하여 dictionary 값으로 반환해줍니다.
test_list = ['a', 'b', 'c', 'a']
print(Counter(test_list))
# 결과: Counter({'a': 2, 'b': 1, 'c': 1})
2. 문자열 안에 동일한 알파벳을 count 하여 dictionary 값으로 반환해줍니다.
test_count = Counter('Hello python')
print(test_count)
# 결과: Counter({'l': 2, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'p': 1, 'y': 1, 't': 1, 'h': 1, 'n': 1})
print(test_count['o'])
# 결과: 2
Counter()에 대해 간략하게 알아보았습니다.
끝.
728x90
'Python' 카테고리의 다른 글
[Python] combinations (0) | 2022.12.28 |
---|---|
[Python] permutations (0) | 2022.12.07 |
[Python] Built-in Functions (0) | 2022.12.01 |
[Python] lambda (0) | 2022.11.22 |
[Python] function (0) | 2022.09.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- bool
- counter
- operators
- index
- Lambda
- find
- Upper
- function
- zip
- Python
- permutations
- Lower
- combinations
- If
- isalpha
- for
- Method
- Built-in Functions
- isdigit
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함