python - 根据字符串对 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]
然而,这很难扩大规模。我正在寻找一种更通用的方法。
解决方案
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]}
推荐阅读
- java - 难以理解 Java 正则表达式解释
- docker - 使用符号链接将日志文件指向 Kubernetes 上的 /proc/1/fd/1 时,STDOUT 日志不起作用
- python - `asyncio.new_event_loop` 的用例是什么?
- swift - “标志”/报告用户功能工作 - Swift / Xcode / Firebase
- javascript - Nodejs express cors错误,在客户端和服务器中都设置了标头
- jquery - 单击链接时动态更改谷歌地图标记文本
- excel - 我想像层次结构一样为每一行提供扩展选项
- python-3.x - 如何在从网站 Python 中提取数据时忽略一类中的文本
- android - 如何使用接口刷新 ViewPager2 中的片段中的数据
- python-3.x - 无法使用 gitpython ImportError