开发者

How can I use python itertools.groupby() to group a list of strings by their first character?

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()? H开发者_开发百科ow 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))


>>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):
    print(i, list(j))


a ['apples', 'apricots']
o ['oranges']
p ['pears', 'peaches']


just another way,

>>> from collections import defaultdict
>>> t=defaultdict(list)
>>> for items in tags:
...     t[items[0]].append(items)
...
>>> t
defaultdict(<type 'list'>, {'a': ['apples', 'apricots'], 'p': ['pears', 'peaches'], 'o': ['oranges']})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜