2016-07-15 72 views
0

我正在使用Python 2.7,僅使用標準模塊。在Python中,所有列表項目都變爲附加項目

我有一個龐大的數據文件,其中包含一堆有關汽車事件的信息。我試圖複製有關單個車輛事件類型(例如加速)的數據並將其寫入單獨的文件。在我將其寫入單獨文件之前,我的當前方法將數據存儲在表中 - 我在列表中使用了列表(請參閱下面的示例表)。

Event Type | Data Location Start | Data Location End 
-------------------------------------------- 
Accelerate | 99     | 181 
Break  | 182     | 263 
Horn  | 264     | 351 
Accelerate | 352     | 434 
...and so on 

The table above in Python would be: 

event_list = [['Accelerate', 99, 181], 
       ['Break', 182, 263], 
       ['Horn', 264, 351], 
       ['Accelerate', 352, 434]] 

問題:我每次追加行,所有其他行更改爲附加行。我在下面提供了我的代碼和控制檯輸出。

#!/usr/bin/python  
""" File Description """ 

import os 

def main(): 
    """ Organize Car Data Into New File """ 

    event_list = []    # This is the entire table 
    first_event = True   # This is a flag 
    single_event = [-1, -1, -1] # This is a single row in the table 
           # [Event Name, Code Line Start, Code Line End] 

    with open('C:/car_event_data.dat', 'rb') as f: 
     line = '-1' 

     while line != '':       # If line = '' then it is EOF 
      line = f.readline() 
      if line[0:6] == 'Event:': 
       if first_event == False:    
        single_event[2] = f.tell() - 1 # Code Line End 
        event_list.append(single_event) # Completed row 
        print(event_list) 
       end = line.find('\x03', 6)   # Find the end location of Event Type 
       single_event[0] = line[6:end]  # Event Type 
       single_event[1] = f.tell()   # Code Line Start 
       first_event = False 

     f.seek(0, os.SEEK_END)      # Put pointer at EOF 
     single_event[2] = f.tell() 
     event_list.append(single_event) 

if __name__ == '__main__': 
    main() 

上面的代碼產生以下輸出:

[['Accelerate', 99, 181]] 
[['Break', 182, 263], ['Break', 182, 263]] 
[['Horn', 264, 351], ['Horn', 264, 351], ['Horn', 264, 351]] 
... and so on 

回答

1

列表的目的是通過在Python引用傳遞。之前添加的元素正在變爲當前行的原因是因爲它們都指向同一個列表single_event。

簡單

single_event = list(range(3)) 
每個之後

追加操作應該能夠解決您的問題。

+0

非常感謝。這解決了問題 –

+0

不客氣。請接受答案(綠色勾號),以幫助代表:) –

相關問題