I have an array of arrays, like this...
[[\'Abradolf Lincler\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\',
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]]
I would use a Counter
>>> from collections import Counter
>>> arrays = [['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]]
>>> result = Counter()
>>> for k, v in arrays:
... result[k] += v
...
>>> result
Counter({'Abradolf Lincler': 32, 'Scary Terry': 20, 'Summer Smith': 20})
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]]
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]]