2017-07-08 93 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基本類型。 –

相關問題