파이썬, groupby (from itertools) 예제
from itertools import groupby
from typing import Any, Iterator
from operator import itemgetter
nums: list[list[int]] = [[1,2],[3,4,5],[6],[7,8,9],[10,11]]
sorted_nums: list[list[int]] = sorted(nums, key=len)
print(f'{sorted_nums=}')
grouped_nums: groupby = groupby(sorted_nums, key=len)
for n, g in grouped_nums:
glist = list(g)
print(len(glist), list(glist))
'''
sorted_nums=[[6], [1, 2], [10, 11], [3, 4, 5], [7, 8, 9]]
1 [[6]]
2 [[1, 2], [10, 11]]
2 [[3, 4, 5], [7, 8, 9]]
'''
words: list[str] = ['Cat','Cactus','Owl','Dog','Orange','Bob','Blue','Bread']
sorted_words = sorted(words, key=len)
print(f'{sorted_words = }')
grouped_words: groupby = groupby(sorted_words, key=lambda s: s[0])
for n, g in grouped_words:
glist = list(g)
print(len(glist), sorted(list(glist)))
'''
sorted_words = ['Cat', 'Owl', 'Dog', 'Bob', 'Blue', 'Bread', 'Cactus', 'Orange']
1 ['Cat']
1 ['Owl']
1 ['Dog']
3 ['Blue', 'Bob', 'Bread']
1 ['Cactus']
1 ['Orange']
'''
grouped_words: groupby = groupby(sorted_words, key=lambda s: s[0])
for letter, g in grouped_words:
print(f'Starts with "{letter}": {list(g)}')
'''
Starts with "C": ['Cat']
Starts with "O": ['Owl']
Starts with "D": ['Dog']
Starts with "B": ['Bob', 'Blue', 'Bread']
Starts with "C": ['Cactus']
Starts with "O": ['Orange']
'''
people: list[dict[str, str | int]] = [
{'name': 'James', 'age': 25, 'city': 'New York'},
{'name': 'Bob', 'age': 30, 'city': 'Chicago'},
{'name': 'David', 'age': 25, 'city': 'New York'},
{'name': 'Sandra', 'age': 23, 'city': 'Chicago'},
{'name': 'Sualchi', 'age': 30, 'city': 'Seoul'},
{'name': 'Sony', 'age': 31, 'city': 'Seoul'},
]
get_city: itemgetter = itemgetter('city')
sorted_cities: list[dict[str, str | int]] = sorted(people, key=get_city)
print(f'{sorted_cities = }')
'''
sorted_cities = [{'name': 'Bob', 'age': 30, 'city': 'Chicago'}, {'name': 'Sandra', 'age': 23, 'city': 'Chicago'}, {'name': 'James', 'age': 25, 'city': 'New York'}, {'name': 'David', 'age': 25, 'city': 'New York'}, {'name': 'Sualchi', 'age': 30, 'city': 'Seoul'}, {'name': 'Sony', 'age': 31, 'city': 'Seoul'}]
'''
grouped_people: groupby = groupby(people, key=get_city)
for city, group in grouped_people:
print(f'{city}:')
for person in group:
print(f' - {person["name"]} (Age: {person["age"]})')
'''
New York:
- James (Age: 25)
Chicago:
- Bob (Age: 30)
New York:
- David (Age: 25)
Chicago:
- Sandra (Age: 23)
Seoul:
- Sualchi (Age: 30)
- Sony (Age: 31)
'''
반응형
'Python 기초' 카테고리의 다른 글
클로저, 람다를 이용한 validator 파이썬 예제 (0) | 2025.01.29 |
---|---|
파이썬, 랜덤 값 다양한 기능 예제 (0) | 2025.01.26 |
파이썬, 유용한 다섯 가지 데코레이터 (0) | 2025.01.20 |
파이썬, f 문자열 기초와 활용 예제 (0) | 2025.01.18 |
파이썬, 비밀번호가 문자/숫자/특수문자 조합이고 8자리 이상 검증 (0) | 2025.01.06 |