简体   繁体   English

使用 for 循环计算此字典中值的总和,不使用 sum() function

[英]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.

相关问题 如何在不使用 sum() 的情况下从每个键中有多个值的字典中的平均值计算平均值? - How do I calculate an average from averages in a dictionary with multiple values in each key without using sum()? 使用python for循环获取txt值并计算值的总和 - Use python for loop to get txt values and calculate the sum of values 用于对字典中的总值求和的函数 - function to sum total values in dictionary 如何在没有明确定义权重的情况下使用字典值计算加权值之和? - How to use dictionary values to calculate sum of weighted values without explicitly defined weights? 如何将 txt.file 中的字符串与我的字典值(值是整数)进行比较并计算总和 - How do I compare the strings in a txt.file to my dictionary values (the values are integers) and calculate the sum 计算字典中的值与另一个嵌套字典中的值之间的乘积之和 - calculate sum of product between values in a dictionary and the other nested dictionary 如何在for循环中使用sum函数? - How to use the sum function in for loop? lambda函数用于对字典中值的乘积求和 - lambda function to sum products of values from a dictionary Python Function 对字典中的偶数值求和 - Python Function sum even values from a dictionary 尝试使用while循环计算数字总和 - Trying to calculate the sum of numbers using while loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM