Make a note of the concise description method of summarizing the sequence of monotonically increasing numbers for each consecutive value.
import itertools
sample = [1,2,3,5,6,7,9,10]
[list(g) for _, g in itertools.groupby(
sample, key=lambda n, c=itertools.count(): n - next(c))]
# => [[1, 2, 3], [5, 6, 7], [9, 10]]
[ʻItertools.groupby](https://docs.python.org/3.9/library/itertools.html#itertools.groupby) passes each element of the iterable of the first argument to the second argument and returns. Returns an iterator that returns consecutive elements with the same value, along with the elements passed to the second argument function. In the above example, the first argument is
sample and the second argument
keyis a lambda expression. Lambda expressions have two arguments,
n and optional
c, but
c has a default value of ʻitertools.count ()
, which is continuous in groupby
. When called when determining the identity of the elements to be used, each element of sample
is passed to n
. ʻItertools.count ()produces an iterator that returns a number incrementing by
1 from
0. The default value of
c is executed only once when the lambda expression is defined, and an iterator that returns the number
+ 1in order from 0 is assigned. So, for
n --next (c),
next (c) increases by
1with each call, so
n increases by
1and the same value is obtained from this lambda expression. It will be returned, but a different value will be returned if
n increases more than
1. The iterator that returns consecutive elements with the same return value of this lambda expression is
g, and
list (g) `generates a list of consecutive elements in a nested list by list comprehension notation.
Recommended Posts