Python:解决“原子学习”的更好逻辑方法

2024-05-01 21:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想改进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)

非常感谢。你知道吗


Tags: of代码inif过程not逻辑upper
3条回答

我建议您查看Python的PLY文档,看看andrewdalke的例子 对于分子的解析例子。(http://www.dalkescientific.com/writings/NBN/parsing_with_ply.html

您可以定义带有原子符号和该原子/符号出现在分子中的时间的代币,例如,对于CH3COOH(醋酸)这样的分子

import lex

tokens = (
   "SYMBOL",
   "COUNT"
         )

t_SYMBOL = (
     r"C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?|P[drmtboau]?|"
     r"H[eofgas]?|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|G[aed]|"
     r"I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|"
     r"U|V|W|Xe|Yb?|Z[nr]"
        )

def t_COUNT(t):
    r"\d+"
    t.value = int(t.value)
    return t



lex.lex()

lex.input("CH3COOH")
for tok in iter(lex.token, None):
    print repr(tok.type), repr(tok.value)

当我运行代码时,我得到了以下信息

'符号'C' '符号'H' “计数”3 '符号'C' '符号'O' '符号'O' '符号'H'

更多信息请点击此处 http://www.dabeaz.com/ply/

这应该能奏效

import re
molecule = 'CH3COOH'
print set(re.findall('[A-Z][a-z]?',molecule))

将打印:

set(['H', 'C', 'O'])

您正在寻找一个正则表达式,该表达式捕获大写字符,后跟可选的小写字符。你知道吗

list(set(re.findall('[A-Z][a-z]?', 'CuBDa')))

但你可能忽略了一些数字,比如二氧化碳,这就可以了

re.findall('[A-Z][a-z]?[0-9]*', 'C4H10FO2P')

如果您只想忽略数字,第一个表达式将起作用

相关问题 更多 >