python list by first first

Lee*_*son 2 python python-itertools divide

list1=['hello','hope','hate','hack','bit','basket','code','come','chess']
Run Code Online (Sandbox Code Playgroud)

我需要的是:

list2=[['hello','hope','hate','hack'],['bit','basket'],['code','come','chess']]
Run Code Online (Sandbox Code Playgroud)

如果第一个字符相同并且是相同的组,则将其子列表.

我怎么解决这个问题?

Ter*_*ryA 13

你可以使用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']]
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案仅适用于对列表进行排序的情况。您可以先对列表进行排序,但性能并不理想。有没有另一个更通用的python库? (4认同)