1

所以我正在读取一个文件并将其存储在变量中,当我到达这一行时:

valP=float(listEleVP)

它返回这个:

ValueError: could not convert string to float: 'r'

这是整个代码:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        a=line.split()

        for items in a:
            listEleVP=items[1]
            listEleVS=items[3]
            valP=float(listEleVP)
            valS=float(listEleVS)
            FinVal=float(valP*valS)
            txtA=items [0]
            txtB=items [2]
            print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

这是输入(.in)文件数据:

Fred 179.0 Luna 0.1654
Layla 131 Mars 0.376
Pat 145.2 Neptune 1.14
END 0 0 0
4

2 回答 2

2
>>> text = """Fred 179.0 Luna 0.1654
... Layla 131 Mars 0.376
... Pat 145.2 Neptune 1.14
... END 0 0 0"""
>>> for line in text.splitlines():
...     a = line.split()
...     for items in a:
...             print items[1], items[3]
... 
r d
7 .
u a
. 6
a l
3
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
IndexError: string index out of range

你应该这样做:

>>> for line in text.splitlines():
...     items = line.split()
...     print items[1], items[3]
... 
179.0 0.1654
131 0.376
145.2 1.14
0 0
于 2013-06-03T20:15:29.263 回答
1

我认为内圈是不必要的:

def main():
    inFile=open('3weightcalc.in','r')
    i=0
    for line in inFile.readlines():
        items=line.split()

        listEleVP=items[1]
        listEleVS=items[3]
        valP=float(listEleVP)
        valS=float(listEleVS)
        FinVal=float(valP*valS)
        txtA=items [0]
        txtB=items [2]
        print("On ",txtB,txtA,"would weigh ",FinVal,"pounds.")
    inFile.close()
main()

问题是在内部循环中,您迭代了split.

希望这可以帮助!

于 2013-06-03T20:15:08.167 回答