python-3.x 将字典中的元组值相乘并取最终和

d6kp6zgx  于 2022-12-15  发布在  Python
关注(0)|答案(4)|浏览(137)

我有一个这样的字典包含元组:

d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}

我如何将每个元组单独相乘,然后取总和?

result = (1 * 0.5) + (2 * 0.3) + (3 * 0.7) = 3.2
sshcrbum

sshcrbum1#

普通Python:

d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
sum_tot = 0
for tpl in d.values():
    prod_tpl = 1
    for item in tpl:
        prod_tpl *= item
    sum_tot += prod_tpl
print(sum_tot)

输出:

3.1999999999999997
guicsvcw

guicsvcw2#

您可以执行以下操作:

from functools import reduce
from operator import mul 

d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}

d1={k:reduce(mul, t) for k,t in d.items()}

>>> sum(d1.values())
3.1999999999999997

或者简单地说:

>>> sum(reduce(mul, t) for t in d.values())
3.1999999999999997

或者,评论中指出的一个更好的方法:

import math
>>> sum(map(math.prod, d.values()))
3.1999999999999997
7kjnsjlb

7kjnsjlb3#

d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
result = 0

for item in d:
    result += d[item][0] * d[item][1]
print(result)
eoigrqb6

eoigrqb64#

d = {'itemA': (1, 0.5), 'itemB': (2, 0.3), 'itemC': (3, 0.7)}
total = 0
for tup in d.values():
    total += tup[0]*tup[1]
print(total)

相关问题