1 回答

TA貢獻1862條經驗 獲得超7個贊
你真的不需要使用groupby來做到這一點。
考慮您的鏈接示例:
list1=['hello','hope','hate','hack','bit','basket','code','come','chess']
您可以創建使用本機 Python 字典描述的組:
groups={}
for word in list1:
groups.setdefault(word[0],[]).append(word)
>>> groups
{'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']}
或者,defaultdict如果您愿意:
from collections import defaultdict
groups=defaultdict(list)
for word in list1:
groups[word[0]].append(word)
>>> groups
defaultdict(<class 'list'>, {'h': ['hello', 'hope', 'hate', 'hack'], 'b': ['bit', 'basket'], 'c': ['code', 'come', 'chess']})
這兩種方法都適用于完全未排序的數據,并根據第一個字母收集單詞。然后,如果需要,您可以自由使用該 dict 的值來制作列表列表:
>>> sorted(groups.values(), key=lambda s: s[0])
[['bit', 'basket'], ['code', 'come', 'chess'], ['hello', 'hope', 'hate', 'hack']]
現在,如果您出于某種原因仍想使用groupby,您可能會執行以下操作:
groups={}
for k,v in groupby(list1, key=lambda s: s[0]):
groups.setdefault(k,[]).extend(v)
添加回答
舉報