2012-08-15 33 views
2

在我的函數中,我創建了我想添加到列表中的唯一變量。但是,無論何時添加下一個變量,列表中所有其他變量的值都會更改爲新的變量。爲什麼我的列表的.append()將每個成員變量的值更改爲新變量?

這裏是我的代碼:

def make_list_of_data_transfer_objects(iFile, eFile, index_of_sheet): 

    iBook = open_workbook(iFile) 
    iSheet = iBook.sheet_by_index(0) 

    eBook = open_workbook(eFile) 
    eSheet = eBook.sheet_by_index(index_of_sheet) 

    DataSet = namedtuple('DataSet', 'line_num data_list') 

    list_objects = [] 
    temp_line_num = 99999 
    temp_data = [0]*5 

    for row_index in range(eSheet.nrows): 
     temp_data[0] = eSheet.cell(row_index,0).value 
     temp_data[1] = eSheet.cell(row_index,1).value 
     temp_data[2] = eSheet.cell(row_index,2).value 
     temp_data[3] = eSheet.cell(row_index,3).value 
     temp_data[4] = eSheet.cell(row_index,4).value 
     for row_index2 in range(iSheet.nrows): 
      if temp_data[0] == iSheet.cell(row_index2,0).value: 
       temp_line_num = row_index2 
       temp_object = DataSet(temp_line_num, temp_data) 

       list_objects.append(temp_object) 

    #print list_objects #every object is the same 

    list_objects.sort(key = lambda tup: tup[0]) #sort by line number 

    return list_objects 

回答

7

變化

temp_object = DataSet(temp_line_num, temp_data) 

temp_object = DataSet(temp_line_num, temp_data[:]) 

temp_object = DataSet(temp_line_num, list(temp_data)) 

通過將temp_data傳遞給DataSet您不需要創建列表的副本,只需重新使用現有的副本即可。通過使用[:]list(),您可以創建一個副本。

+1

實際上'temp_object'是一個'DataSet'(不管是什麼);相反,我認爲OP需要將'temp_object = DataSet(temp_line_num,temp_data)'改爲'temp_object = DataSet(temp_line_num,temp_data [:])'。 (或者更改'DataSet'構造函數以在第二個參數中創建數據副本) – 2012-08-15 19:31:03

+0

@EdwardLoper:是的,在這裏拍攝臀部。良好的捕獲,更新。 – 2012-08-15 19:32:41

相關問題