如何使用 python itertools.groupby() 按第一个字符对字符串列表进行分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2472001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:44:01  来源:igfitidea点击:

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

pythonstringitertools

提问by Adam Ziolkowski

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

我应该如何使用 itertools.groupby() 按每个字符串中的第一个字符对该列表进行分组?我应该如何提供 itertools.groupby() 所需的“key”参数?

回答by Ignacio Vazquez-Abrams

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

回答by Pratik Deoghare

You might want to create dictafterwards:

您可能想在dict之后创建:

from itertools import groupby

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

回答by SilentGhost

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


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

回答by ghostdog74

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