If I get 3 lists
List1 = ["A","B","C"] List2 = [1,2,3] List3 = [4,5,6]
How can I assign and sum List2 & List3 to List1 so that
A = 5 B = 7 c = 9
If I get 3 lists
List1 = ["A","B","C"] List2 = [1,2,3] List3 = [4,5,6]
How can I assign and sum List2 & List3 to List1 so that
A = 5 B = 7 c = 9
Use a dictionary comprehension:
>>> {key: a + b for key, a, b in zip(List1, List2, List3)} {'A': 5, 'C': 9, 'B': 7}
I must admit your question was confusing. Maybe you are looking for this instead?
>>> List1 = [a + b for a, b in zip(List2, List3)] >>> List1 [5, 7, 9]
You can zip
List2
and List3
to get
[(1, 4), (2, 5), (3, 6)]
you can then sum individual tuples with sum
function like this
List1 = map(sum, zip(List2, List3)) print List1 # [5, 7, 9]
If you are looking for a way to create a dictionary out of it, you can simply zip
the List1
and the sum
values which we calculated with map
and sum
to get
zip(List1, map(sum, zip(List2, List3))) # [('A', 5), ('B', 7), ('C', 9)]
And if we pass that to the dict
function, we get a new dictionary :)
dict(zip(List1, map(sum, zip(List2, List3)))) # {'A': 5, 'C': 9, 'B': 7}
>>> total=[] >>> List1 = ["A","B","C"] >>> List2 = [1,2,3] >>> List3 = [4,5,6] >>> for i in range(len(List2)): total.append(List2[i]+List3[i]) >>> total #[5, 7, 9] >>>dic={} >>> for i in range(len(List1)): dic.update({List1[i]:total[i]}) >>> dic #{'A': 5,'C': 9,'B': 7}