forked from twtrubiks/python-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupby_tutorial.py
More file actions
27 lines (21 loc) · 799 Bytes
/
groupby_tutorial.py
File metadata and controls
27 lines (21 loc) · 799 Bytes
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
from itertools import groupby
'''
ref. https://docs.python.org/3.6/library/itertools.html#itertools.groupby
itertools.groupby(iterable, key=None)
'''
if __name__ == "__main__":
things = [("apple", "bear"),
("cherry", "bear"),
("banana", "duck"),
("cherry", "bear"),
("banana", "cactus"),
("cherry", "bear"),
("cherry", "bear"),
("apple", "speed boat"),
("apple", "school bus"), ]
# Generally, the iterable needs to already be sorted on the same key function. important!!
things = sorted(things, key=lambda x: x[0])
for key, group in groupby(things, lambda x: x[0]):
print('key', key)
print('group', list(group))
print('==================')