Reputation: 23
inp = [['t', 80, 500.0], ['g', 135, 1500.0], ['t', 80, 8000.0],['g', 170, 1500.0],['g', 135, 1000.0]]
If first two values are the same sum 3rd value and save new items in a new list like this: inp1 = [['t', 80, 8500.0], ,['g', 170, 1500.0],['g', 135, 2500.0]]
Upvotes: 1
Views: 73
Reputation: 11938
Alternatively...
In [19]: temp = defaultdict(int)
In [20]: for i, j, k in inp:
...: temp[(i,j)] += k
...:
In [21]: res = [[*t[0], t[1]] for t in temp.items()]
In [22]: res
Out[22]: [['t', 80, 8500.0], ['g', 135, 2500.0], ['g', 170, 1500.0]]
Upvotes: 1
Reputation: 9207
inp = [['t', 80, 500.0], ['g', 135, 1500.0], ['t', 80, 8000.0],['g', 170, 1500.0],['g', 135, 1000.0]]
dic = {x+"-"+str(y):z for (x,y,z) in inp}
inp1 = [x[0].split("-") + [sum([n[2] for n in inp if x[0]==n[0]+"-"+str(n[1])])] for x in dic.items()]
print(inp1)
# [['t', '80', 8500.0], ['g', '135', 2500.0], ['g', '170', 1500.0]]
Upvotes: 1