typestar

itertools.groupby in Python

Collapsing consecutive equal items into groups.

import itertools

text = "aaabbbccd"
runs = [(ch, len(list(group)))
        for ch, group in itertools.groupby(text)]

people = [("nz", "kiri"), ("nz", "tane"), ("au", "riley")]
by_country = {}
for country, group in itertools.groupby(people, key=lambda p: p[0]):
    by_country[country] = [name for _, name in group]

How it works

  1. groupby(text) yields each run and its members.
  2. Counting the group gives run-length encoding.
  3. A key function groups records by a field.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
304
Tokens
106
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 4 of 5 in Generators & itertools, step 13 of 53 in Pythonic Python.

← Previous Next →