I have a list of tuples as seen below :
l = [(1,'Nick'),(4,'George'),(4,'George'),(3,'Nick')]
what i would like to do is merge the tuples with the same Name and add the corresponding numbers. Result here should be :
l_res = [(4,'Nick'),(8,'George')]
How could this be done using python?
CodePudding user response:
You can use a combination of set and list comprehensions like this:
>>> l = [(1,'Nick'),(4,'George'),(4,'George'),(3,'Nick')]
>>> unique = set(e[1] for e in l)
>>> [(sum([x[0] for x in l if x[1] == n]), n) for n in unique]
[(8, 'George'), (4, 'Nick')]
CodePudding user response:
You can use an intermediate set as suggested in a previous answer or with an intermediate dictionary like this:
l = [(1,'Nick'),(4,'George'),(4,'George'),(3,'Nick')]
d = dict()
for v, t in l:
d[t] = d.get(t, 0) v
result = [(v, k) for k, v in d.items()]
print(result)
Output:
[(4, 'Nick'), (8, 'George')]
CodePudding user response:
Probably the cleanest way is by using a Counter dictionary.
from collections import Counter
l = [(1,'Nick'),(4,'George'),(4,'George'),(3,'Nick')]
sum_dict = Counter()
for el in l:
sum_dict[el[1]] = el[0]
print(sum_dict) # Output: Counter({'George': 8, 'Nick': 4})
If you really want a list of tuples (which doesn't seem like the best datatype for this data), you can easily convert it with list comprehension over dict.items()
sum_list = [(v,k) for k,v in sum_dict.items()]
print(sum_list) # Output: [('Nick', 4), ('George', 8)]
CodePudding user response:
You want to turn l_res
into a dict by name, adding the numbers:
dic = {}
for tup in l:
num, name = tup
if name in dic:
dic[name] = num
else:
dic[name] = num
to turn it back into a list:
l_res = [(dic[k], k) for k in dic]