-2

Combine list elements

I'm working on python list and ran into a problem. I have a list of tuple.

oldlist= [('A', 30), ('B', 20), ('A', 10), ('B', 20), ('C', 20), ('D', 10), ('B', 40)]

How can I merge them and add up the number regarding to their letter. For example, total A score is 30 + 10 = 40 B score is 20 + 20 + 40 = 80 ... so on and so on.

I want my new list looks like this

newlist = [('A', 40),('B', 80),('C',20),('D',10)]
  • 6
    Can you demonstrate *any* effort at solving this yourself? – Scott Hunter Jan 12 '21 at 02:51
  • I create an new empty list, then add each individual character into it. My goal is to have a list of unique character. temp_list = [(A),(B),(C),(D)] Then I loop through the old list using temp_list item. Then I will add everything up if the value in oldlist match with the Item in my temp_list item. – Gibson Howard Jan 12 '21 at 02:56

4 Answers4

0

I suggest using a dictionary, like so:

dictionary = {}
for element in oldlist:
    if element[0] in dictionary:
        dictionary[element[0]] += element[1]
    else:
        dictionary[element[0]] = element[1]

If you need it in a list, add this:

newlist = list(dictionary.items())
Armadillan
  • 530
  • 3
  • 15
0

Use itertools.groupby and operator.itemgetter:

from itertools import groupby
from operator import itemgetter
oldlist= [('A', 30), ('B', 20), ('A', 10), ('B', 20), ('C', 20), ('D', 10), ('B', 40)]
newlist = [(x, sum(list(zip(*y))[1])) for x, y in groupby(sorted(oldlist, key=itemgetter(0)), key=itemgetter(0))]
print(newlist)

Output:

[('A', 40), ('B', 80), ('C', 20), ('D', 10)]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can do something like this:

my_dict = {}
for i in oldlist:
    my_dict[i[0]] = my_dict.get(i[0], 0) + i[1]
output = list(my_dict.items())

gives

[('A', 40), ('B', 80), ('C', 20), ('D', 10)]
Jarvis
  • 8,494
  • 3
  • 27
  • 58
0

perhaps this may be useful.

oldlist= [('A', 30), ('B', 20), ('A', 10), ('B', 20), ('C', 20), ('D', 10), ('B', 40)]
def results(results_list):
    result_dict = {}
    for name, mark in results_list:
        result_dict[name] = result_dict.get(name, 0) + mark
    return list(result_dict.items())

print(results(oldlist))

The output is,

[('A', 40), ('B', 60), ('C', 20), ('D', 10)]
nectarBee
  • 401
  • 3
  • 9