使用for循环计算这个字典中值的总和,不使用sum()函数?
Dictionary = {"001": {"a" : [1, 5, 6], "b" : [2, 8, 9] }, "002": {"c" : [6.89, 5.67, 1.24], "d" : [9.32, 6, 78] }}
我试着回答这个问题在许多方法,但我总是得到这个错误:
TypeError: unsupported operand type(s) for +: 'int' and 'dict'
谢谢你!
根据数据结构使用嵌套循环:
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
我想你是想用操作数+对字典求和相反,你需要获取列表中的每一个数字(提醒一下,列表在一个字典中,而这个字典在另一个字典中)所以我写了一个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)