Adith Kumar
Adith Kumar

Reputation: 11

Adding two lists by addition based on keys

I was thinking of performing addition in lists.

listA = ['a', 'b', 'a', 'b']
listB = [1, 3, 5, 7]

using zip I get

listC = [['a', 1], ['b', 3], ['a', 5], ['b', 7]]

My goal is to get

listC = [['a', 6], ['b', 10]]

I remember Scala has a nice map function. But I tried applying the same to python, but I am unable to get any idea on modification.

Upvotes: 0

Views: 90

Answers (6)

ted
ted

Reputation: 14724

Easiest way would be to use a dictionary:

listA = ['a', 'b', 'a', 'b']
listB = [1, 3, 5, 7]

result = {}
for k, v in zip(listA, listB):
    result[k] = result.get(k, 0) + v
result = [list(items) for items in result.items()]
# or
result = list(map(list, result.items()))

Upvotes: 0

SSharma
SSharma

Reputation: 953

You can build dictionary while reading the two lists:

listA = ['a', 'b', 'a', 'b']
listB = [1, 3, 5, 7]

result = {}
for A, B in zip(listA, listB):
    if A in result:
        result[A] += B
    else:
        result[A] = B
result = result.items()
print(result)

This should give you your result: dict_items([('a', 6), ('b', 10)])

Upvotes: 1

han solo
han solo

Reputation: 6590

You could just use defaultdict from collections like,

>>> ListA
['a', 'b', 'a', 'b']
>>> ListB
[1, 3, 5, 7]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for key,val in zip(ListA, ListB):
...   d[key] += val
... 
>>> list(d.items())
[('a', 6), ('b', 10)]

Upvotes: 2

Sushanth
Sushanth

Reputation: 2342

Here is a code that will do the job:

ListA = ['a', 'b', 'a', 'b']
ListB = [1, 3, 5, 7]
output={}
for index,key in enumerate(ListA):
    if key in output:
        output[key]+=ListB[int(index)]
    else:
        output[key]=ListB[int(index)]
final_out = [[k, v] for k, v in output.items()]
print(final_out)

Output:

[['a', 6], ['b', 10]]

Upvotes: 0

user2390182
user2390182

Reputation: 73460

Using a collections.defaultdict:

from collections import defaultdict

d = defaultdict(int)
for a, b in zip(ListA, ListB):
    d[a] += b

list(d.items())
# [('a', 6), ('b', 10)]

Upvotes: 1

Fruity Medley
Fruity Medley

Reputation: 564

Try this: get a list of each unique key by turning ListA into a set.

Keys = set(ListA)
# ['a, 'b']

Then you can use list enumeration to sum up each occurance

List C = [sum([v for j, v in zip(ListA, ListB) if j == k]) for k in Keys]

Upvotes: 0

Related Questions