Recognise similar instances in array and merge them

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

    Consider using a dictionary to keep track of score sums for each player:

    scores = [['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]]
    
    grouped_scores = {}
    for name, score in scores:
        if name not in grouped_scores: grouped_scores[name] = score
        else: grouped_scores[name] += score
    

    Then you can get back the results as a list of lists:

    merged_scores = [list(t) for t in grouped_scores.items()]
    print(merged_scores)
    # [['Summer Smith', 20], ['Scary Terry', 20], ['Abradolf Lincler', 32]]
    

提交回复
热议问题