How to assign from one list to another?

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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

回答1:

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]


回答2:

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}


回答3:

     >>> 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}


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!