嵌套字典求和所有值

2024-09-27 23:16:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个看似简单的问题,却解决不了。在

Dictionary = {
    'own': {
        'Dun Morogh': {
            'Horde': {
                'chars': {
                    'Qiidu': {
                        'auction': 1
                        }
                    }
                 }
            }, 
        'Tirion': {
            'Alliance': {
                'chars': {
                    'Qiip': {
                        'auction': 1
                         }
                     }
                 }
            }, 
        'Proudmoore': {
            'Alliance': {
                'chars': {
                    'Qiip': {
                        'mail': 1
                        }
                    }
                }
            } 
        }, 
    'name': u'Rascal-Bot'
}

这是我在字典中使用的格式,我想遍历它,对其中的所有整数求和并返回它。在

我的代码:

^{pr2}$

这在“打印”上有效,但我如何将其调整为“总结”?在


Tags: namedictionarymailownauctionalliancecharsdun
2条回答

您可以添加一个sum变量来跟踪总和,并让您的函数返回该值。递归调用将把“sub sums”加起来并返回给调用者,调用者将把它们加到它们的总计中,直到您返回到第一个调用和总计。在

def findTotal(self, dct):
    total = 0
    for key, value in dct.iteritems():
        if isinstance(value, int):
            total += value
        if isinstance(value, dict):
            total += self.findTotal(value)
    return total

如果使用递归函数,则需要返回调用堆栈的总和:

def findTotal(self, dct):
    total = 0
    for key, value in dct.iteritems():
        if isinstance(value, int):
            total += value
        if isinstance(value, dict):
            total += self.findTotal(value)
    return total

或者,您可以递归到每个选项,并检查是否有端子箱:

^{pr2}$

相关问题 更多 >

    热门问题