嵌套字典:嵌套为字典值的字典的同一键的值的总和



我想对同一键的值求和:根据字典composition对字符串输入H, C, O, N, S,这是字母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'

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

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

sum()函数文档中:

sum(iterable[, start])

总和从左到右开始和可迭代对象的项,并返回总计。start默认为0

Counter对象求和时,请为其提供一个空Counter()以开始:

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

如果然后将结果分配给分配给out字典中的,则会得到预期结果Counter实例:

>>> 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})}

三个嵌套的 for 循环应该可以完成这项工作。

out = {}
for x in string_input: # for each string in list
current = out[x] = {}
for char in x: # for each character in the string
cur_composition=composition[char]
for val in cur_composition: # for all the entry in the composition dictionary for that character
current[char]= cur_composition[val] if val not in current[char] else cur_composition[val]+current[char]

相关内容

  • 没有找到相关文章

最新更新