首页 > 解决方案 > 根据字符串对 dict 值列表求和

问题描述

我有一本字典如下:

m = {
        'A':[71.03711,71.0788],
        'R':[156.10111,156.1875],
        'N':[114.04293,114.1038],
        'D':[115.02694,115.0886],
        'C':[103.00919,103.1388],
        'E':[129.04259,129.1155],
        'Q':[128.05858,128.1307],
        'G':[57.02146,57.0519],
        'H':[137.05891,137.1411],
        'I':[113.08406,113.1594],
        'L':[113.08406,113.1594],
        'K':[128.09496,128.1741],
        'M':[131.04049,131.1926],
        'F':[147.06841,147.1766],
        'P':[97.05276,97.1167],
        'S':[87.03203,87.0782],
        'T':[101.04768,101.1051],
        'W':[186.07931,186.2132],
        'Y':[163.06333,163.1760]
    }

我有这个字符串 s。我想计算总和如下:

s = "ARWYLKNI"

total1 = 0
total2 = 0

for a in s:
    total1 = total1 + m[a][0]
    total2 = total2 + m[a][1]

然而,这很难扩大规模。我正在寻找一种更通用的方法。

标签: python

解决方案


print ([sum(l) for l in zip(*[m[a] for a in s])])

输出:

[1044.58687, 1045.2522]

要扩大规模:

sl = ["ARWYLKNI","AFVYLKNI","ARWDLKNI"]

print ([[sum(l) for l in zip(*[m[a] for a in s])] for s in sl])

输出:

[[1044.58687, 1045.2522], [1044.58687, 1045.2522], [1044.58687, 1045.2522]]

如果您希望返回 dict:

print (dict(zip(sl,[[sum(l) for l in zip(*[m[a] for a in s])] for s in sl])))

输出:

{'ARWYLKNI': [1044.58687, 1045.2522], 'AFYLKNI': [849.47486, 850.0281], 'ARWDLKNI': [996.55048, 997.1648000000001]}

推荐阅读