python list group by first character

亡梦爱人 提交于 2019-12-06 11:10:54

You can use itertools.groupby:

>>> from itertools import groupby
>>> list1 = ['hello','hope','hate','hack','bit','basket','code','come','chess']
>>> [list(g) for k, g in groupby(list1, key=lambda x: x[0])]
[['hello', 'hope', 'hate', 'hack'], ['bit', 'basket'], ['code', 'come', 'chess']]

Expanding on TerryA's answer:

To create a dict with the first letter as key and the matching elements as value, you can do

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

This also works if list1 is not sorted (as shown) and it can, of course, also be converted to a list of lists again with

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

You can do that with partition_by function from my funcy library:

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

Note that this will only work if list1 is already sorted, as with itertools.groupby. If list1 is unsorted than sorting it and then partitioning would be inefficient, the better way would be to use group_by function:

from funcy import group_by
list2 = group_by(0, list1).values()

In Python 3.7+ (i.e. a version where dictionaries maintain insertion order) you could simply use a dict of lists keyed by the first character to group the words. This works with both sorted and unsorted input:

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