识别数组中的相似实例并将其合并 [英] Recognise similar instances in array and merge them
问题描述
我有一个数组数组,像这样...
I have an array of arrays, like this...
[['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]]
我希望能够扫描每个数组,如果数组中已经存在元素0,则将它们合并并将第一个元素添加在一起.因此,例如,有5个Summer Smith实例.代码应该识别出它是同一位玩家,因此将所有Summer Smith得分相加,从而使Summer Smith总得分为20.它应该为每个玩家做到这一点.因此,一切看起来都像
I want to be able to scan through the each array and if element 0 already exists in array, merge them and add the first element together. So for example, there are 5 instances of Summer Smith. The code should recognise that its the same player and therefore add all the Summer Smith scores so making the total Summer Smith score 20. It should do that for each player. So it all looks like for example,
[['Harry',20], ['Jake', 16]]....
我试图...
for array in arrays:
if array[0] in [not sure what to do now]
推荐答案
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]]
这篇关于识别数组中的相似实例并将其合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!