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
實際上'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
@EdwardLoper:是的,在這裏拍攝臀部。良好的捕獲,更新。 – 2012-08-15 19:32:41