'Combine tuples in a list and get sum of second tuple element [duplicate]
I have a list of tuples:
tupples = [('d2', 1),
('d2', 1), ('d3', 1), ('d10', 1), ('d10', 1), ('d15', 1),
('d165', 1), ('d165', 1), ('d172', 1),('d2', 1)]
I want to combine like elements at 0, and sum all elements at 1 so the output looks like:
###[('d2',3),('d165',2),('d10',1),('d3',1),('d15',1),('d172',1)
new =[]
for item in tupples:
if item[0] in item:
sums = sum[item[1]]
new.append((item[0],item1[1]))
Solution 1:[1]
What about using pandas.DataFrame.groupby ?
>>> import pandas as pd
>>> list(pd.DataFrame(tupples).groupby(0).sum().to_dict()[1].items())
[('d10', 2), ('d15', 1), ('d165', 2), ('d172', 1), ('d2', 3), ('d3', 1)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | keepAlive |
