Path = "C:/Users/Kailash/Downloads/Results_For_Stride-Table.csv"
f = open(Path, "r") # as infile: #open("C:/Users/Kailash/Downloads/25ft_output.csv", "w") as outfile:
counter = 0
n = 0
distance = float
print("n =", n)
while True:
counter += 1
#print("Counter = ", counter)
lines = f.readline()
Stride_Length = lines.split(", ")
# if (distance > 762):
# Delta_t = distance
# print("Pre-Delta_t = ", Delta_t)
distance[n] += float(Stride_Length[3])
#n += 1
if distance > 762:
Delta_t = 762 - distance[n - 1]
print("Delta_t = ", Delta_t)
Residual_distance = distance - 762
print("Residual_distance = ", Residual_distance)
counter = 0
distance = Residual_distance
print("Counter & Distance RESET!")
print(distance)
我收到一个TypeError:'type'对象在行中不可订阅: distance [n] + = float(Stride_Length [3]) 知道为什么我会看到这个吗?
答案 0 :(得分:0)
你犯了一些错误。首先,float
是类型。您可以通过在其名称后添加括号()
来实例化此类型的对象:
distance = float()
现在,distance
包含值0.0
。这是一个不可变的对象。 distance
不一个可以使用值索引的列表。如果要创建列表,则必须使用以下语法:
distances = [] # note the plural
接下来,您正在读取文件。使用for
循环有一种更简单的方法:
for line in open(Path, 'r'):
....
您可以通过调用.append
函数将元素添加到列表中。默认情况下,列表不会预先分配元素,因此对不存在的元素执行+=
会抛出错误。
最后,您不需要数百个计数器。在任何时候你似乎都想要distances
的最后一个元素。您只需distances[-1]
即可访问它。
这里有一些应该有用的代码:
Path = "C:/Users/Kailash/Downloads/Results_For_Stride-Table.csv"
distances = []
for line in open(Path, "r"):
Stride_Length = line.split(", ")
distances.append(float(Stride_Length[3]))
if distances[-1] > 762:
Delta_t = 762 - distances[-2]
print("Delta_t =", Delta_t)
Residual_distance = distances[-1] - 762
print("Residual_distance =", Residual_distance)
distances[-1] = Residual_distance
print("Counter & Distance RESET!")
print(distances[-1])
在复制并粘贴此代码之前,请尝试了解它与您目前的代码有何不同,以及如何在此基础上进行构建。