파이썬, 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)
'''
반응형

+ Recent posts