2017-07-08 69 views
0

新到Python

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) 

我得到一个类型错误: '类型' 对象未在所述线标化的: 距离[N] + =浮子(Stride_Length [3] ) 任何想法,为什么我看到这个?类型错误:类型对象不是标化的

+0

你可能想用'distance = float(0)'开始?那么,n环路部分应该如何处理距离? – PRMoureu

+0

这个问题的答案是:看看[this](https://stackoverflow.com/questions/26920955/typeerror-type-object-is-not-subscriptable-when-indexing-in-to-a-dictionary)链接。 –

+0

@PRMoureu:我试着用float(0)替换distance = float但是没有解决。 'n'必须每次增加。对不起,#必须删除。 –

回答

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]) 

之前您复制并粘贴此代码,请试着去了解它从你目前有什么不同,以及如何建立在此。

+0

另外,[参考](https://stackoverflow.com/help/someone-answers)。 –

+0

@PRMoureu Lmao,谢谢你的注意。 –

+0

“这是一个不可变的对象(类似于Java中的基本类型,如果可以涉及)”。这非常非常误导。 Python中没有像Java的基本类型那样存在。 Python是一种纯粹的OO语言。换句话说,Python数字类型就像是Java原始类型的盒装等价物。另外,考虑一个不变的'frozenset',但非常不像Java基本类型。 –

相关问题