在Python中成为新手...我想设计一个程序来计算原子质量,给定这样的分子'C14-H10-O'。
(我知道,已经创建了非常漂亮的程序,但是我想创建自己的程序,并为自己感到骄傲。)
我的代码快完成了,但是我发现了我无法解决的问题。
这是我的代码:
masas = {'H': 1.007825,'C': 12.01,'O': 15.9994,'N': 14.0067,'S': 31.972071,'P': 30.973762}
elements_list = ['H','C','O','N','S','P']
def calcula_masa_atomica(molecula):
"""
Calcula la masa atomica de una molecula
"""
import re
masa = 0.0
#Primero creamos los
molecula = re.sub('[-]','',molecula) #Remove "-"
molecula = (re.split('(\d+)',molecula))#split numbers and elements
for i,ch in enumerate(molecula):
if ch in elements_list: #If the element is in the elements_list,element_mass = masas.get(ch)# Get the mass of this element
if molecula[i + 1].isdecimal(): #If the inmediately item is decimal
masa += element_mass * int(molecula[i + 1])# Add the mass of this element by the number of times that element is present. In each iteration,the masses of each element will be added and stored in the mass object
# If not,just add that element's mass to the sum.
else:
masa += element_mass
return masa
没问题的是,如果某些元素在该元素之后没有一位数字,则该分子看起来像'C14-H10-O2',但是Python会回答此错误。
IndexError:列表索引超出范围
我知道我有什么问题,但我不知道如何解决。