Recognise similar instances in array and merge them

前端 未结 4 1244
余生分开走
余生分开走 2021-01-24 17:59

I have an array of arrays, like this...

[[\'Abradolf Lincler\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\',         


        
4条回答
  •  时光说笑
    2021-01-24 18:24

    Better using setdefault:

    d={}
    for x,y in arrays:
       d.setdefault(x,[]).append(y)
    print(list(map(list,{k:sum(v) for k,v in d.items()}.items())))
    

    Output:

    [['Abradolf Lincler', 32], ['Scary Terry', 20], ['Summer Smith', 20]]
    

    Best in all defaultdict:

    from collections import defaultdict
    d=defaultdict(int)
    for x,y in arrays:
       d[x]+=y
    print(list(map(list,dict(d).items())))   
    

    Output:

    [['Abradolf Lincler', 32], ['Scary Terry', 20], ['Summer Smith', 20]]
    

提交回复
热议问题