嵌套字典:将字典中相同键的值的总和嵌套为字典值 [英] Nested dictionary: sum values of same key of the dictionaries nested as a value of dictionary

查看:95
本文介绍了嵌套字典:将字典中相同键的值的总和嵌套为字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据字典composition的字母输入的总和,将相同的键的值求和:H, C, O, N, S是字母A, C, D, E的组合.

I want to sum values of the same key: H, C, O, N, S according to dictionary composition for the string input which is a combination of letter A, C, D, E.

composition = {
    'A':  {'H': 5, 'C': 3, 'O': 1, 'N': 1},
    'C':  {'H': 5, 'C': 3, 'O': 1, 'N': 1, 'S': 1},
    'D':  {'H': 5, 'C': 4, 'O': 3, 'N': 1},
    'E':  {'H': 7, 'C': 5, 'O': 3, 'N': 1},
}

string_input = ['ACDE', 'CCCDA']

预期结果应该是

out = {
    'ACDE' : {'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1},
    'CCCDA' : {'H': 15, 'C': 9, 'O': 3, 'N': 3, 'S': 3},
}

我正在尝试使用Counter,但停留在unsupported operand type(s) for +: 'int' and 'Counter'

I am trying to use Counter but stuck at unsupported operand type(s) for +: 'int' and 'Counter'

from collections import Counter

for each in string_input:
  out = sum(Counter(composition[aa]) for aa in each)

推荐答案

sum()具有起始值,从该起始值开始求和.如果在第一个参数中没有要求和的值,这也将提供一个默认值.起始值为0,是整数.

sum() has a starting value, from which it starts the sum. This also provides a default if there are no values to sum in the first argument. That starting value is 0, an integer.

sum()函数文档:

sum(iterable[, start])

求和 start iterable 的项,并返回总数. start 默认为0.

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0.

在对Counter个对象求和时,请给它一个空的Counter()以开头:

When summing Counter objects, give it an empty Counter() to start off with:

sum((Counter(composition[aa]) for aa in each), Counter())

如果您随后将结果分配给分配给out字典中的,则可以得到作为Counter实例的预期结果:

If you then assign the result to a key in a dictionary assigned to out you get your expected result as Counter instances:

>>> out = {}
>>> for each in string_input:
...     out[each] = sum((Counter(composition[aa]) for aa in each), Counter())
...
>>> out
{'ACDE': Counter({'H': 22, 'C': 15, 'O': 8, 'N': 4, 'S': 1}), 'CCCDA': Counter({'H': 25, 'C': 16, 'O': 7, 'N': 5, 'S': 3})}

这篇关于嵌套字典:将字典中相同键的值的总和嵌套为字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆