嵌套字典:将字典中相同键的值的总和嵌套为字典值
我想根据字典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})}