Home > OS >  Check the index position and adding values of another list of corresponding index
Check the index position and adding values of another list of corresponding index

Time:05-29

I have two lists, one with string and another with integer.

a = ['A', 'B', 'A', 'B']

b = [-1, 2, 1, 3]

I need to add the values of b such that it takes the index position from list a.

Result: A-> 0, B-> 5

CodePudding user response:

zip the two lists together so you can associate the values in a with the corresponding values in b. For example:

>>> a = ['A', 'B', 'A', 'B']
>>> b = [-1, 2, 1, 3]
>>> for x in set(a):
...     print(f"{x} -> {sum(j for i, j in zip(a, b) if x == i)}")
...
A -> 0
B -> 5

Or to build the results as a dict (more efficient since you can do this in a single iteration instead of a nested iteration):

>>> ab = {i: 0 for i in a}
>>> for i, j in zip(a, b):
...     ab[i]  = j
...
>>> ab
{'A': 0, 'B': 5}

Or as a dict of lists if you want to keep the individual b values distinct so you can do other things with them:

>>> ab = {i: [] for i in a}
>>> for i, j in zip(a, b):
...     ab[i].append(j)
...
>>> ab
{'A': [-1, 1], 'B': [2, 3]}
>>> {a: sum(b) for a, b in ab.items()}
{'A': 0, 'B': 5}
>>> {a: int.__mul__(*b) for a, b in ab.items()}
{'A': -1, 'B': 6}

CodePudding user response:

Use a defaultdict:

a = ['A', 'B', 'A', 'B']
b = [-1, 2, 1, 3]

from collections import defaultdict 

d = defaultdict(int)
for k,v in zip(a,b):
    d[k]  = v

dict(d)

Output: {'A': 0, 'B': 5}

  • Related