gpt4 book ai didi

python - 列表索引未在 for 循环中更新(python)

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:05 26 4
gpt4 key购买 nike

在单独的定义中,我试图获取 ')' 的索引,然后反向循环,直到得到 '('。反向语句正在工作,并且该语句继续保留在 ')' 的第一个索引上。索引无法更新的原因是什么?

class elements:
periodic_table = ['']

def __init__(self, equation):
self.equation = equation

def poly(self):
polyatomic = 'C2H3O2', 'HCO3', 'HSO4', 'ClO', 'ClO3', 'ClO2', 'OCN', 'CN', 'H2PO4', 'OH', 'NO3', 'NO2', 'ClO4', 'MnO4', 'SCN',
return polyatomic

def separate(self):
element = elements.equation
list1 = []

for first, second in zip(element, element[1:]):
if first == ')' and second.isdigit():
multiply = int(second)
print(first, second)
print(element.index(first))
for multiplcation in element[element.index(first)::-1]:
if multiplcation == '(':
break
elif multiplcation != ')':
final = multiplcation * multiply
print(final)
if first == '=':
list1.append(first)
elif first.isupper() and second.islower():
list1.append(first + second)
elif first.isupper() and second.isdigit():
amount = first * int(second)
list1.append(amount)
elif first.isupper():
list1.append(first)


elements = elements(
'K4Fe(CN)6 + KMnO4 + H2SO4 = KHSO4 + Fe2(SO4)3 + MnSO4 + HNO3 + CO2 + H2O')

print(elements.separate())

最佳答案

问题的症结在这里:

            for multiplcation in element[element.index(first)::-1]:

您正在从字符串中第一次出现 RPAREN 进行备份,而不是从刚刚找到的 RPAREN 进行备份。在给定的示例中,您将总是返回遍历“CN”以查找任何后面的括号。

我建议你重新设计你的代码:将方程拆分成分子;编写一个函数来返回每个分子的展开式。如果您需要重构整个方程,请将它们连接在一起。

这应该可以帮助您解决当前的问题。

关于python - 列表索引未在 for 循环中更新(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58440681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com