I have a list of strings similar to this list:
tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches')
How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?
You might want to create dict
afterwards:
from itertools import groupby
d = {k: list(v) for k, v in groupby(sorted(tags), key=lambda x: x[0])}
groupby(sorted(tags), key=operator.itemgetter(0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With