Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list group by first character

list1=['hello','hope','hate','hack','bit','basket','code','come','chess']

What I need is:

list2=[['hello','hope','hate','hack'],['bit','basket'],['code','come','chess']]

If the first character is the same and is the same group, then sublist it.

How can I solve this?

like image 318
Lee_Prison Avatar asked Aug 28 '26 04:08

Lee_Prison


2 Answers

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']]
like image 100
TerryA Avatar answered Aug 29 '26 18:08

TerryA


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']]
like image 34
nspo Avatar answered Aug 29 '26 16:08

nspo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!