jdcaba
jdcaba

Reputation: 143

How to join values between sublists

I have a list with sublists, for example:

LA=[[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]]

If the first element in each sublist is an ID, how do I join the ones with the same ID to get something like this:

LR=[[1,11],[2,10],[4,8],[6,5]]

I've tried using a for loop, but it's too long and not efficient.

Upvotes: 0

Views: 94

Answers (4)

RoadRunner
RoadRunner

Reputation: 26315

Grouping with collections.defaultdict() is always straightforward:

from collections import defaultdict

LA = [[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]]

# create defaultdict of list values
d = defaultdict(list)

# loop over each list
for sublist in LA:

    # group by first element of each list
    key = sublist[0]

    # add to dictionary, each key will have a list of values
    d[key].append(sublist)

# definitely can be more readable
result = [[key, sum(x[1] for x in [y for y in value])] for (key, value) in sorted(d.items())]
print(result)

Output:

[[1, 11], [2, 10], [4, 8], [6, 5]]

Upvotes: 1

tim-mccurrach
tim-mccurrach

Reputation: 6815

You can do it just using list comprehensions:

LR = [[i,sum([L[1] for L in LA if L[0]==i])] for i in set([L[0] for L in LA])]

Gives the desired result.

To break this down a bit set([L[0] for L in LA]) gives a set (with no repeats) of all of the ID's, then we simply itterate over that set and sum the values which also have that ID.

Upvotes: 2

ababuji
ababuji

Reputation: 1731

LA=[[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]]

new_dict = {}
for (key, value) in LA:
    if key in new_dict:
        new_dict[key].append(value)
    else:
        new_dict[key] = [value]


for key, value in new_dict.items():

    new_dict[key] = (sum(value))

dictlist = []

for key, value in new_dict.items():
    temp = [key,value]
    dictlist.append(temp)

print(dictlist)

will do the job too

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can use itertools.groupby:

import itertools
LA=[[1,2],[2,7],[4,5],[1,9],[6,5],[4,3],[2,1],[2,2]]
new_d = [[a, sum(i[-1] for i in list(b))] for a, b in itertools.groupby(sorted(LA), key=lambda x:x[0])]

Output:

[[1, 11], [2, 10], [4, 8], [6, 5]]

Upvotes: 2

Related Questions