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

筅森魡賤 提交于 2019-11-27 12:34:13

问题


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()?


回答1:


groupby(sorted(tags), key=operator.itemgetter(0))



回答2:


You might want to create dict afterwards:

from itertools import groupby

d = {k: list(v) for k, v in groupby(tags, key=lambda x: x[0])}



回答3:


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


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



回答4:


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']})


来源:https://stackoverflow.com/questions/2472001/how-can-i-use-python-itertools-groupby-to-group-a-list-of-strings-by-their-fir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!