如何在列表中将系数与其变量分开?

时间:2015-10-20 03:10:17

标签: python python-2.7

所以,我的问题比标题所暗示的要多一些。我正在编写一个程序来计算化合物的摩尔质量。到目前为止,我已经开始研究化学化合物,每种元素中只有一种像NaCl,但我需要能够计算H2O等物质的质量。这是我到目前为止的代码:

import re
atomic_wt = {'Na':22.99, 'Cl':35.45, 'H':1.008, 'O':16}
input = raw_input()
elementList = (re.findall('[A-Z][^A-Z]*', input))
wt_list = []

for element in elementList:
    elem_wt = atomic_wt[element]
    wt_list.append(elem_wt)

#    print elem_wt

print "%sg" % sum(wt_list)

当我输入像H2O这样的东西时,它会返回错误,说H2不在我的字典中。你怎么建议我把H和2分开?并且,你如何建议我告诉它在添加之前将元素的值乘以它们的系数?

1 个答案:

答案 0 :(得分:1)

我在您的代码中进行了一些修改,以便使用正则表达式从您正在取出的元素中分离出系数。

import re
atomic_wt = {'Na':22.99, 'Cl':35.45, 'H':1.008, 'O':16}
input = raw_input()
elementList = (re.findall('[A-Z][^A-Z]*', input))
wt_list = []

for element_withcoeff in elementList:
    #Separate the coefficients
    coeffList = re.findall(r'\d+', element_withcoeff)
    if len(coeffList) < 1:
        coeff = 1 #If no coefficent is defined use 1 as default 
    else:
        coeff = int(coeffList[0])

    #Separate the element name for dictionary lookup
    element = filter(lambda c: not c.isdigit(), element_withcoeff)
    print coeff, element

    #Calculate using coeff
    elem_wt = coeff * atomic_wt[element]
    wt_list.append(elem_wt)

print "%sg" % sum(wt_list)

注意:我不是化学专业的学生,​​所以要确保计算摩尔质量的逻辑是否正确。