Not surprisingly known !? Python standard library functions groupby

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.

Basic usage

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

Not surprisingly known !? Python standard library functions groupby
Not surprisingly known! ?? What about the arguments of built-in functions? What school are you from? [Python]
Python functions
Python standard library: second half (Python learning memo ⑨)
Python standard library: First half (Python learning memo ⑧)
Python 3.6 email library
[Python] Standard input
Python Library notes
#Python basics (functions)
[Beginner] Python functions
Python Easy-to-use functions
Python basics: functions
Can be used in competition pros! Python standard library
[Redash] Standard library cannot be used in python function