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)