I have a data list structure looking like this:
[('a', 1),('a', 2),('b', 0),('b', 1),('c', 0)]
I’m trying to combine the second value of tuple if the first item is same. (And remove the duplicate)
End result should be:
[('a', 3),('b', 1),('c', 0)]
My approach is to create a second empty list and check if first element exist in list, if not then append. Otherwise loop through second list and add value of [1] item in iteration from first list to [1] item in second list. I am unable to get my concept working. If anyone has a more efficient solution I am also open to suggestion.
secondList = []
for item in firstList:
if (secondList.count(item[0]]):
secondList.append(item)
else:
for item_j in secondList:
if (item_j[0] == item[0]):
item_j[1] = item_j[1]+item[1]