Recognise similar instances in array and merge them

前端 未结 4 1248
余生分开走
余生分开走 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:06

    You can use itertools.groupby for this:

    from itertools import groupby
    l = [['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Scary Terry', 4], ['Scary Terry', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Summer Smith', 4], ['Abradolf Lincler', 4], ['Summer Smith', 4], ['Summer Smith', 4]]
    
    res = [[name, sum(s[1] for s in score)] for name, score in groupby(sorted(l, key=lambda x: x[0]), key=lambda x: x[0])]
    

    Which is equivalent to the loop:

    res = []
    for name, score in groupby(sorted(l, key=lambda x: x[0]), key=lambda x: x[0]):
        res.append([name, sum(s[1] for s in score)])
    

    and returns:

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

提交回复
热议问题