0

用户将输入化学式。例如CO2OHC5H18COO,或类似的东西。C = 12.01然后,输出将是给定 , ,H = 1.008的分子量O = 16。到目前为止我有这个:

while(True):

    chemical_formula = input("Enter chemical formula, or enter to quit: ")

    length = len(chemical_formula)
    if chemical_formula == "":
        break
    else:
        char = list(chemical_formula)
        length = len(char)
        for i in char:
            if i == "C":
                c = 12.0107
            elif i == "H":
                h = 1.00794
            elif i == "O":
                o = 15.9994
            else:
                if char[i-1] == "C":
                    print(float(i)*c)
                elif char[i-1] == "H":
                    print(float(i)*h)
                elif char[i-1] == "O":
                    print(float(i)*o)
            

但我不明白为什么我不能(i-1)用来获取 for 循环中的前一个元素,所以我可以将它乘以数字。有没有其他方法可以获取字符串的前一个元素?或者也许有不同的方法来解决这个问题?

4

1 回答 1

0

您必须迭代索引而不是元素,如下例所示:

chemical_formula = input("Enter chemical formula, or enter to quit: ")

length = len(chemical_formula)
if chemical_formula == "":
    break
else:
    char = list(chemical_formula)
    length = len(char)
    for i in range(length):
        if char[i] == "C":
            c = 12.0107
        elif char[i] == "H":
            h = 1.00794
        elif char[i] == "O":
            o = 15.9994
        else:
            if char[i-1] == "C":
                print(float(i)*c)
            elif char[i-1] == "H":
                print(float(i)*h)
            elif char[i-1] == "O":
                print(float(i)*o)
于 2013-05-22T08:59:25.660 回答