1

Here I have a list of list:

[['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]]

How can i get a list of:

[['a', 3], ['b', 3.1],['c', 6.2],]

I could only think of some very clumpsy way. looping the list with set() but is there a more efficient way?

5 Answers 5

4

You can use a dictionary to store the values for each key. Then, make a list of lists from the dictionary elements.

data = [['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]]

mapper = {}
for pair in data:
    key, val = pair
    mapper[key] = mapper.get(key, 0) + val

data_merged = list(map(list, mapper.items()))
print(data_merged)

Output:

[['a', 3], ['b', 3.1], ['c', 6.2]]

Explanation:

  • Declares an empty dictionary (mapper).
  • Iterates each pair of elements.
  • If the key is already in the dictionary then increase it by given value. Otherwise, set it is as the initial value.
  • Creates a list of lists from the dictionary items.
Sign up to request clarification or add additional context in comments.

4 Comments

+1, this works even when unsorted; but i believe list(map(list, mapper.items())) is equivalent to list(mapper.items()).
Using collections.defaultdict(int), it would work with mapper[key] += val
@MustafaAydın, thanks. FYI, list(mapper.items()) returns a list of tuples of the elements. The OP wants a list of lists that is the reason to use list(map(list, mapper.items())).
@arsho big thanks! i think i solved it with your method!
2

If that list is sorted by its first elements as seen, then itertools.groupby does the job:

from itertools import groupby

[[key, sum(lst[1] for lst in group)] for key, group in groupby(a, key=lambda e: e[0])]

We group by the first entry of the sub lists. Then for each group, we sum the second elements and put them in a list along with the corresponding key which is the first element i.e. the letter we grouped on. The list comprehension gives the total answer thereby.

Comments

1

This is probably what you want but it's not very pretty:

my_list = [['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]]
[[key, sum(l[1] for l in my_list if l[0]==key)] for key in set([l[0] for l in my_list])]

2 Comments

a one liner without importing anything, +1! But i think some explanation about set and the inner list comprehension would help fasten the process of understanding it.
Thanks @MustafaAydın! Looks like our solutions are actually very similar. Your explanation kinda explains my answer too :D.
1

This is how you can solve it using pandas:

import pandas as pd

df = pd.DataFrame([['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]],columns = ['Letter','Value'])
df.groupby(['Letter']).sum().reset_index().values.tolist()

Comments

1

You can also use a defaultdict with a default value of 0:

from collections import defaultdict

data = [['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]]

sums = defaultdict(int)
for key, value in data:
    sums[key] += value
    
out = [[key, value] for key, value in sums.items()]

print(out)
# [['a', 3], ['b', 3.1], ['c', 6.2]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.