파이썬[Python]: itertools - groupby 함수

파이썬(Phthon): itertools 모듈 - groupby 함수(function)


/// 설명

반복 가능한 객체(iterable)로 부터 키와 그룹(list)으로 된 이터레이터를 만들어 줍니다. key 함수는 객체의 각 요소에 적용되며, 일반적으로는 해당 key 함수로 정렬을 한 후 사용합니다.

※ 형식
itertools.groupby(iterable, key=None)

reference
https://docs.python.org/3/library/itertools.html#module-itertools

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import itertools
 
test_str = 'abcdABCeASEhhi'
 
test_func = str.lower
test_sorted = sorted(test_str, key=test_func)
print(test_sorted)  # ['a', 'A', 'A', 'b', 'B', 'c', 'C', 'd', 'e', 'E', 'h', 'h', 'i', 'S']
 
test_key = []
test_group = []
 
for k, g in itertools.groupby(test_sorted, test_func):
    test_key.append(k)
    test_group.append(list(g))
 
print(test_key)  # ['a', 'b', 'c', 'd', 'e', 'h', 'i', 's']
print(test_group)  # [['a', 'A', 'A'], ['b', 'B'], ['c', 'C'], ['d'], ['e', 'E'], ['h', 'h'], ['i'], ['S']]
 
cs

* 실행환경: Microsoft Windows 10 Homes
* 인터프리터: 파이썬(Python 3.9)


– 당신을 응원합니다. –

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

파이썬[Python]: 내장함수 - bit_length 메서드

C 언어: sin 함수, cos 함수, tan 함수