我正试图把一串类似于这个"N4++e=>N2+N2"的化学式转换成这个"N4+ + e => N2 + N2"。但我要处理的是"++“
我的代码现在看起来是这样的:
temp = "N4++e=>N2+N2"
lhs = temp.split("=>")[0]
rhs = temp.split("=>")[1]
# only showing code for the left hand side
temp = lhs.split("+")
temp1 = []
for i in range(len(temp)):
if temp[i]=='':
temp1[i-1] = temp[i-1] + "+"
else:
temp1.append(temp[i])
lhs = temp1在这段代码之后,我得到了类似于lhs = 'N4+','e‘的东西,我可以按我想要的方式把它组合在一起。
但是否有更好、更快的替代方案?我可以有相当长的化学反应清单。
发布于 2022-06-16 17:00:34
我可能建议通过多个replace操作来实现这一点,例如:
temp = "N4++e=>N2+N2"
print(temp.replace("+", " + ").replace(" + +", "+ +").replace("=>", " => "))
# N4+ + e => N2 + N2尽管如此,对于您可能得到的输入类型和您想要实现的结果,这做了很多假设。为了获得更健壮的解决方案,您可能需要考虑编写一个lexer (例如,使用铺层)。
https://stackoverflow.com/questions/72648185
复制相似问题