我想要simsec_0
中每个字符串的值,这是通过用字典monoisotopicaa_dict
中的浮点替换所有字符来计算的
peptides_report = {'simsec_0': ['CCYYK', 'TTSS']}
monoisotopicaa_dict = {"C":103.00919,"E":129.04259,"Q":128.05858, \
"K":128.09496,"M":131.04049,"F":147.06841, \
"S":87.03203,"T":101.04768,"W":186.07931,"Y":163.06333}
预期结果类似于
{'simsec_0':[['CCYYK',660.24], ['TTSS',376.15942]]}
所以我尝试编写函数CALC
用字典中的float替换每个字符串p_v_each
def CALC(peptides_report, monoisotopicaa_dict):
for p_k, p_v in peptides_report.iteritems():
for p_v_each in p_v:
for mono_each in monoisotopicaa_dict.keys():
# May be replace with number and "+"
# string = p_v_each.replace(mono_each, monoisotopicaa_dict[mono_each])
xxx = CALC(peptides_report, monoisotopicaa_dict)
我应该如何处理字符串以获取值并能够对它们求和?
答案 0 :(得分:2)
你可以简单地使用这样一个事实:字符串是一个字符集合,并提取sum
中的值并理解:
>>> values = {"C":103.00919,"E":129.04259,"Q":128.05858, \
... "K":128.09496,"M":131.04049,"F":147.06841, \
... "S":87.03203,"T":101.04768,"W":186.07931,"Y":163.06333}
>>> values
{'Q': 128.05858, 'C': 103.00919, 'E': 129.04259, 'T': 101.04768, 'W': 186.07931, 'F': 147.06841, 'Y': 163.06333, 'K': 128.09496, 'M': 131.04049, 'S': 87.03203}
>>> sum(values[l] for l in 'CCYYK')
660.2400000000001
>>> sum(values[l] for l in 'TTSS')
376.15942
>>> [sum(values[l] for l in word) for word in ['CCYYK', 'TTSS']]
[660.2400000000001, 376.15942]
将值放入dict中:
report = {'simsec_0': ['CCYYK', 'TTSS']}
monoisotopicaa = {"C":103.00919,"E":129.04259,"Q":128.05858, \
"K":128.09496,"M":131.04049,"F":147.06841, \
"S":87.03203,"T":101.04768,"W":186.07931,"Y":163.06333}
def value(word):
return sum(monoisotopicaa[l] for l in word)
{k:[[w, value(w)] for w in v] for k,v in report.items()}
# {'simsec_0': [['CCYYK', 660.2400000000001], ['TTSS', 376.15942]]}