乘以同一个词的关键词

时间:2016-11-13 15:04:34

标签: python python-3.x dictionary list-comprehension dict-comprehension

我正在使用python 3.5, 我需要乘以这个dict,这应该输出dict的每个键的乘法结果。

{0: [0.0008726003490401396, 0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0017452006980802793, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396], 1: [0.007853403141361256, 0.008726003490401396, 0.0008726003490401396], 2: [0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.007853403141361256, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0008726003490401396, 0.0017452006980802793, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0034904013961605585, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.002617801047120419, 0.0008726003490401396, 0.0034904013961605585, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396, 0.0008726003490401396]}

这是我的尝试,但不起作用:

lista = {k: [v*v for v in v] for k, v in lista.items()}

输出我将是例如:

{0: [0.068726003490401396], 1: [0.077853403141361256, 2: [0.098363001745200698]}

1 个答案:

答案 0 :(得分:3)

使用词典理解和functools.reduce + operator.mul

>>> from functools import mul
>>> mul(3, 4)  # == 3 * 4
12

>>> from functools import reduce
>>> reduce(mul, [3, 4, 2])  # == (3 * 4) * 2
24
>>> from functools import reduce
>>> from operator import mul
>>>
>>> lista = {
...     0: [0.0008726003490401396, 0.004363001745200698],
...     1: [0.007853403141361256, 0.008726003490401396, 0.0008726003490401396],
...     2: [0.004363001745200698, 0.0008726003490401396, 0.0008726003490401396],
... }
>>>
>>> {key: reduce(mul, value) for key, value in lista.items()}
{0: 3.8071568457248673e-06, 1: 5.979827506374137e-08, 2: 3.322126392430076e-09}
>>> {key: [reduce(mul, value)] for key, value in lista.items()}
{0: [3.8071568457248673e-06], 1: [5.979827506374137e-08], 2: [3.322126392430076e-09]}