我有一个程序可以找到一些数据并对数据运行一个基本的数学函数,但是当我运行它时,我收到以下错误:ValueError: invalid literal for float(): Timestep:
。错误发生在我调用map(float,line.split()[1:])
的行中。
有谁知道为什么以及如何解决此错误。
#!/usr/bin/python
l=[]
with open("movie.xyz") as f:
line = f.next()
nat = int(line.split()[0])
print nat
f.next()# skip headers
for line in f:
if line.strip():
l.append(map(float,line.split()[1:])) # make all values floats
#print l[0][0]
b = 0
a = 1
for b in range(55):
for a in range(b+1,56):
import operator
import numpy as np
#vector1 = l[b]
vector1 = (l[b][0],l[b][1],l[b][2])
vector2 = (l[a][0],l[a][1],l[a][2])
#print('vector 1 = %' % vector1)
#print('vector 1 = (%f,%f,%f)' % vector1)
#print vector2
x = vector1
y = vector2
vector3 = list(np.array(x) - np.array(y))
#print vector3
dotProduct = reduce( operator.add, map( operator.mul, vector3, vector3))
dp = dotProduct**.5
print dp
前几行数据看起来像:
2805
Atoms. Timestep: 0
Cu 46.7176 27.1121 27.1121
Cu 43.2505 36.0618 32.4879
Cu 43.3392 36.0964 28.9236
Cu 43.2509 37.8362 27.1091
Cu 43.3406 36.0958 25.2957
Cu 43.2582 36.0629 21.737
Cu 43.2505 32.4879 36.0618
答案 0 :(得分:1)
插入
import pdb; pdb.set_trace()
在此行之前,看看是什么给了你line.split()[1:]
pdb =提示调试器:https://docs.python.org/2/library/pdb.html
或者这样做:
if line.strip():
try:
l.append(map(float,line.split()[1:]))
except ValueError:
print "Value error at: ", line.split()[1:]
使此代码工作添加此功能:
def foo(value):
try:
result = float(value)
except ValueError:
print "cant parse %r into float" %value
result = None
return result
并替换该行:
l.append(map(float,line.split()[1:]))
为:
l.append(map(foo, line.split()[1:]))