我想改进Python中的代码。我在这里寻找一个逻辑帮助,用更少的代码得到同样的结果。你知道吗
我的过程通过参数获取一串原子并“学习”它们,返回它所学习的原子列表。你知道吗
我想知道是否有任何方法来优化我的代码。你知道吗
def mol_term(molecule):
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
list_of_atoms = []
for i in range(len(molecule) - 1): #goes all string long
if molecule[i] in upper:
if not molecule[i+1] in upper:
temp = molecule[i] + molecule[i+1] #if atom has two letters
i = i + 1
else:
temp = molecule[i] #if not
if not temp in list_of_atoms:
list_of_atoms.append(temp) #if atom is not in the list appends to it
if molecule[-1] in upper:
list_of_atoms.append(molecule[-1]) #checks last letter
return print(list_of_atoms)
非常感谢。你知道吗
我建议您查看Python的PLY文档,看看andrewdalke的例子 对于分子的解析例子。(http://www.dalkescientific.com/writings/NBN/parsing_with_ply.html)
您可以定义带有原子符号和该原子/符号出现在分子中的时间的代币,例如,对于CH3COOH(醋酸)这样的分子
当我运行代码时,我得到了以下信息
'符号'C' '符号'H' “计数”3 '符号'C' '符号'O' '符号'O' '符号'H'
更多信息请点击此处 http://www.dabeaz.com/ply/
这应该能奏效
将打印:
您正在寻找一个正则表达式,该表达式捕获大写字符,后跟可选的小写字符。你知道吗
但你可能忽略了一些数字,比如二氧化碳,这就可以了
如果您只想忽略数字,第一个表达式将起作用
相关问题 更多 >
编程相关推荐