...
/groupby(), islice() and starmap()
groupby(), islice() and starmap()
Let's figure out the iterators that do not terminate. i.e. groupby(), islice() and starmap().
We'll cover the following...
groupby(iterable, key=None)
The groupby
iterator will return consecutive keys and groups from
your iterable. This one is kind of hard to wrap our heads around without seeing an example.
So let’s take a look at one!
Press + to interact
from itertools import groupbyvehicles = [('Ford', 'Taurus'), ('Dodge', 'Durango'),('Chevrolet', 'Cobalt'), ('Ford', 'F150'),('Dodge', 'Charger'), ('Ford', 'GT')]sorted_vehicles = sorted(vehicles)for key, group in groupby(sorted_vehicles, lambda make: make[0]):for make, model in group:print('{model} is made by {make}'.format(model=model,make=make))print ("**** END OF GROUP ***\n")
Here we import groupby
and then create a list of tuples. Then we sort the data so it makes more sense when we output it and it also let’s groupby
actually group items correctly.
Next we actually loop over the
iterator returned by groupby
which gives us the key and the group. Then
we loop over the group and print out what’s in it.
Just for ...