简体   繁体   English

如何在字典中乘以列表元素

[英]How to Multiply list elements in dictionary

I have two Dictionaries as mentioned below, I need to multiply each element in the list of dictionaries with respective element of the list of other dictionary and print result. 我有两个如下所述的字典,我需要将字典列表中的每个元素与其他字典和打印结果列表中的各个元素相乘。 I have managed to multiply one list, How do I make it dynamic? 我设法将一个列表相乘,如何使其变得动态?

dict1 = {0: [1, 1, 0, 1, 1, 0], 1: [1, 0, 1, 1, 1, 0]}

dict2 = { 0: [16, 0, 2, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}

result = { 0: [16, 0, 0, 0, 0, 0], 1:[15, 0, 0, 0, 1, 0]}

from operator import mul
result = list( map(mul, dict1[0], dict2[0]) )

You can zip each of the lists together and use a dict comprehension like this: 您可以将每个列表压缩在一起,并使用像这样的字典理解:

result = {i :[x*y for x, y in zip(dict1[i], dict2[i])] for i in dict1.keys()}

This assumes that dict1 and dict2 share the same keys 假设dict1和dict2共享相同的密钥

Welcome stack user, 欢迎堆栈用户,

You can use DICT COMPREHENSIONS to do it. 您可以使用DICT COMPREHENSIONS来做到这一点。 No zip required. 无需拉链。

from operator import mul

dict1 = {0: [1, 1, 0, 1, 1, 0], 1: [1, 0, 1, 1, 1, 0]}
dict2 = {0: [16, 0, 2, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}

result = {key: list(map(mul, dict1[key], dict2[key])) for key in dict1.keys() }

result
{0: [16, 0, 0, 0, 0, 0], 1: [15, 0, 0, 0, 1, 0]}

PEP 274 -- Dict Comprehensions https://www.python.org/dev/peps/pep-0274/ PEP 274-听写理解https://www.python.org/dev/peps/pep-0274/

It reads something like: For each key in the list of keys, make a dictionary from key and list(map(mul, dict1[key], dict2[key])) 它的内容类似于:对于键列表中的每个键,请从键和列表中创建一个字典(map(mul,dict1 [key],dict2 [key]))

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM