The Python standard library module itertools provides convenient functions for handling iterators. Among them, groupby is often used, but I will introduce it because many people do not know it. ..
groupby
A function that groups iterables (lists, iterators, etc.) with arbitrary keys. The return value is an iterator for the key and the elements that belong to the key.
The iterable passed to groupby must have consecutive elements with the same key, so it must be sorted in advance.
It's hard to get an image just by explaining, so let's take a look at a simple sample.
This is an example of grouping a list with a tuple of letters and numbers as an element.
from itertools import groupby
from operator import itemgetter
a = [("b", 3), ("a", 1), ("c", 2), ("a", 2), ("b", 1)]
a = sorted(a, key=itemgetter(0))
for (k, g) in groupby(a, key=itemgetter(0)):
print("key:" + k)
for item in g:
print(item)
Execution result
key:a
('a', 1)
('a', 2)
key:b
('b', 3)
('b', 1)
key:c
('c', 2)
If you use groupby without sorting, you will get the following.
:If you run it without sorting...
key:b
('b', 3)
key:a
('a', 1)
key:c
('c', 2)
key:a
('a', 2)
key:b
('b', 1)
Recommended Posts