我有一个看起来像这样的行集:
defaultdict(,
{
u'row1': {u'column1': 33, u'column2': 55, u'column3': 23},
u'row2': {u'column1': 32, u'column2': 32, u'column3': 17},
u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
})
我希望能够轻松获得column1,column2,column3的总和.如果我可以为任意数量的列执行此操作会很棒,在哈希映射中接收结果看起来像columnName => columnSum.正如您可能猜到的那样,我不可能首先从数据库中获取求和值,因此提出问题的原因.
解决方法:
>>> from collections import defaultdict
>>> x = defaultdict(dict,
{
u'row1': {u'column1': 33, u'column2': 55, u'column3': 23},
u'row2': {u'column1': 32, u'column2': 32, u'column3': 17},
u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
})
>>> sums = defaultdict(int)
>>> for row in x.itervalues():
for column, val in row.iteritems():
sums[column] += val
>>> sums
defaultdict(, {u'column1': 96, u'column3': 58, u'column2': 174})
哦,更好的方式!
>>> from collections import Counter
>>> sums = Counter()
>>> for row in x.values():
sums.update(row)
>>> sums
Counter({u'column2': 174, u'column1': 96, u'column3': 58})
标签:python,sum
来源: https://codeday.me/bug/20190723/1513400.html