我有一个包含元组的字典:
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
Plain 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
你可以这样做:
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
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)
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)