[英]Using a for loop Calculate the sum of the values in this dictionary and do not use sum() function
Using a for loop Calculate the sum of the values in this dictionary and do not use sum() function?使用for循环计算这个字典中值的总和,不使用sum() function?
Dictionary = {"001": {"a" : [1, 5, 6], "b" : [2, 8, 9] }, "002": {"c" : [6.89, 5.67, 1.24], "d" : [9.32, 6, 78] }}
Ive tried to answer this in many methods but i always get this error:我试图用很多方法回答这个问题,但我总是收到这个错误:
TypeError: unsupported operand type(s) for +: 'int' and 'dict'
Thank you !谢谢 !
Use a nested loop according to the data structure:根据数据结构使用嵌套循环:
total = 0
for dct in Dictionary.values(): # the outermost dict's values are dicts again ...
for lst in dct.values(): # ... whose values are lists ...
for num in lst: # ... whose elements are addable numbers
total += num
total
# 138.12
I think you was trying to make a sum the dictionary with the operand + Instead you need to get every single number inside of the list (remind that the list is inside of a dictionary and this dictionary is inside of another) So i make a for loop:我想你是想用操作数 + 对字典求和而不是你需要得到列表中的每个数字(提醒列表在字典中而这个字典在另一个字典中)所以我做了一个 for环形:
Dictionary = {"001": {"a": [1, 5, 6], "b": [2, 8, 9]}, "002": {"c": [6.89, 5.67, 1.24], "d": [9.32, 6, 78]}}
for c in range(0, len(Dictionary['001'])):
l1 = Dictionary['001']['a']
l2 = Dictionary['001']['b']
som1 = l1[c] + l2[c]
for c in range(0, len(Dictionary['002'])):
l1 = Dictionary['002']['c']
l2 = Dictionary['002']['d']
som2 = l1[c] + l2[c]
somt = som1 + som2
print(somt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.