2

我正在使用python 3.5, 我需要乘這個字典,這應該輸出字典的每個鍵的乘法結果。相同字典的乘法鍵

{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()} 

i的輸出將是例如:

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

而不是內部列表理解,看看python的「降低」功能 –

回答

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]} 
+0

感謝answer..but 0.0008726003490401396 * 0.004363001745200698 =不moltiplication .. –

+0

@DavideDiMenna的結果,那麼,你能詳細期望值如何計算? – falsetru

+0

你是對的人!現在我嘗試去做..不是沒有導入的方式嗎? –