python列表按第一个字符分组

python列表按第一个字符分组,python,itertools,divide,Python,Itertools,Divide,我需要的是: list1=['hello','hope','hate','hack','bit','basket','code','come','chess'] 如果第一个字符相同且为同一组,则将其子列表 如何解决此问题?您可以使用: 您可以使用my library中的函数执行此操作: 请注意,只有当list1已经排序时,这才有效,就像itertools.groupby一样。如果list1是未排序的,而不是排序的,那么分区将是低效的,更好的方法是使用函数: from funcy import

我需要的是:

list1=['hello','hope','hate','hack','bit','basket','code','come','chess']
如果第一个字符相同且为同一组,则将其子列表

如何解决此问题?

您可以使用:

您可以使用my library中的函数执行此操作:

请注意,只有当
list1
已经排序时,这才有效,就像
itertools.groupby
一样。如果
list1
是未排序的,而不是排序的,那么分区将是低效的,更好的方法是使用函数:

from funcy import partition_by
list2 = partition_by(0, list1)

扩展TerryA的答案:

要创建以第一个字母为键、匹配元素为值的dict,可以执行以下操作

from funcy import group_by
list2 = group_by(0, list1).values()
如果列表1未排序(如图所示),这也会起作用,当然,也可以使用

>>> list1=['hello','hope','hate','hack','bit','basket','code','come','chess', 'archetype', 'cheese']
... mydict={}
... for k, g in groupby(list1, key=lambda x: x[0]):
...    if k in mydict:
...        mydict[k] += g
...    else:
...        mydict[k]=list(g)
... print(mydict)
{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'a': ['archetype'], 'c': ['code', 'come', 'chess', 'cheese']}
在Python3.7+(即字典保持插入顺序的版本)中,您可以简单地使用由第一个字符键入的列表的dict对单词进行分组。这适用于已排序和未排序的输入:

>>> [v for k, v in mydict.items()]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['archetype'], ['code', 'come', 'chess', 'cheese']]

@Lee_监狱Itertools非常酷:)。如果你想看,就看一看;我链接了文档:)作为lambda的替代方案,您可能需要使用
操作符。itemgetter(0)
此解决方案仅在列表排序时有效。您可以先对列表进行排序,但性能并不理想。还有其他更通用的python库吗?@josiah可能看到我的答案了,如果列表末尾有“hack”这个词呢?
>>> list1=['hello','hope','hate','hack','bit','basket','code','come','chess', 'archetype', 'cheese']
... mydict={}
... for k, g in groupby(list1, key=lambda x: x[0]):
...    if k in mydict:
...        mydict[k] += g
...    else:
...        mydict[k]=list(g)
... print(mydict)
{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'a': ['archetype'], 'c': ['code', 'come', 'chess', 'cheese']}
>>> [v for k, v in mydict.items()]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['archetype'], ['code', 'come', 'chess', 'cheese']]
list1 = ['hello', 'hope', 'hate', 'bit', 'basket', 'code', 'come', 'chess', 'hack']
d = {}

for word in list1:
    d.setdefault(word[0], []).append(word)
list2 = list(d.values())
print(list2)
# [['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']]