我有这个:
a = [['huhu', 'dow'], ['haha', 'dow'], ['haha', 'pow'], ['haha', 'dow'], ['haha', 'mat'], ['hihi', 'dow'], ['hihi', 'pow']]
我想要
[[' huhu',' dow'],[' haha',' dow',' pow' ;,' dow',' mat'],[' hihi', ' dow'],[' hihi',' pow']]
答案 0 :(得分:2)
我建议在这里使用字典,它更干净。特别推荐collections.defaultdict
:
from collections import defaultdict
dct = defaultdict(list)
for key, *values in a:
dct[key].extend(values)
输出:
defaultdict(list,
{'huhu': ['dow'],
'haha': ['dow', 'pow', 'dow', 'mat'],
'hihi': ['dow', 'pow']})
如果你想把它作为一个列表,这是一个相当简单的理解:
[[k, *v] for k, v in dct.items()]
# [['huhu', 'dow'], ['haha', 'dow', 'pow', 'dow', 'mat'], ['hihi', 'dow', 'pow']]