[英]function to sum total values in dictionary
我有一个字典,其中包含多个输入值。
inventory = {847502: ['APPLES 1LB', 2, 50], 847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50], 485034: ['BELL PEPPERS 1LB', 3, 50]}
我想创建一个函数来获取所有值项,即。 sum((2 * 50)+(1 * 100)等...)我想我快到了,但是这似乎只会加上第一个值...。
def total_and_number(dict):
for values in dict.values():
#print(values[1]*values[2])
total =0
total += (values[1]* values[2])
return(total)
total_and_number(inventory)
返回和总行放错了位置。 这将返回650。
inventory = {847502: ['APPLES 1LB', 2, 50],
847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50],
485034: ['BELL PEPPERS 1LB', 3, 50]
}
def total_and_number(dict):
total = 0
for values in dict.values():
total += values[1]*values[2]
return(total)
total_and_number(inventory)
采用:
def total_and_number(d):
tot = 0
for k, v in d.items():
tot += v[1]*v[2]
return tot
total_and_number(inventory)
您应该为循环代码定义变量合计。
result = sum([ value[1]*value[2] for value in inventory.values()]
要么
def total_and_number(dict):
total =0
for values in dict.values():
#print(values[1]*values[2])
total += (values[1]* values[2])
return total
total_and_number(inventory)
尝试这个:
x = {
847502: ['APPLES 1LB', 2, 50], 847283: ['OLIVE OIL', 1, 100], 839529: ['TOMATOS 1LB', 4, 25],
483946: ['MILK 1/2G', 2, 50], 493402: ['FLOUR 5LB', 2, 50], 485034: ['BELL PEPPERS 1LB', 3, 50]
}
print(sum([x[i][1]*x[i][2] for i in x.keys()]))
输出:
C:\Users\Desktop>py x.py
650
编辑:对于您自己的代码,您需要取出total=0
并从循环中return total
。
def total_and_number(dict):
total = 0
for values in dict.values():
total += (values[1]*values[2])
return(total)
print(total_and_number(x))
输出:
C:\Users\Desktop>py x.py
650
看起来每个值都是以下项的列表(尽管它可能应该是元组):
itemname, qty, eachprice
因此,迭代和直接求和应该足够容易:
sum(qty*eachprice for _, qty, eachprice in inventory.values())
您应该尝试通过其键值访问这些项目:
def total_and_number(dictis):
total = 0
for key in list(dictis.keys()):
print(key)
total += (dictis[key][1]*dictis[key][2])
return(total)
它确实返回您需要的期望值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.