合并并删除相同的密钥python

时间:2018-06-12 07:02:13

标签: python merge key python-3.6

我有这个:

 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']]

1 个答案:

答案 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']]