为什么我的列表的.append()改变每一个成员变量的值到新的变量? [英] Why is my list's .append() changing the value of every member variable to the new variable?
本文介绍了为什么我的列表的.append()改变每一个成员变量的值到新的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的功能,我创造,我要添加到列表中唯一变量。但每当我追加下一个变量,列表切换到新的里面所有其他变量的值。
下面是我的code:
高清make_list_of_data_transfer_objects(iFile的,电子文件,index_of_sheet): iBook的= open_workbook(iFile的)
iSheet = iBook.sheet_by_index(0) 电子书= open_workbook(电子文件)
eSheet = eBook.sheet_by_index(index_of_sheet) 数据集= namedtuple(数据集,line_num DATA_LIST') list_objects = []
temp_line_num = 99999
temp_data = [0] * 5 在范围(eSheet.nrows)ROW_INDEX:
temp_data [0] = eSheet.cell(ROW_INDEX,0)。价值
temp_data [1] = eSheet.cell(ROW_INDEX,1)。价值
temp_data [2] = eSheet.cell(ROW_INDEX,2)。价值
temp_data [3] = eSheet.cell(ROW_INDEX,3)。价值
temp_data [4] = eSheet.cell(ROW_INDEX,4)。价值
在范围(iSheet.nrows)row_index2:
如果temp_data [0] == iSheet.cell(row_index2,0).value的:
temp_line_num = row_index2
temp_object =数据集(temp_line_num,temp_data) list_objects.append(temp_object) #PRINT list_objects #every对象是相同的 list_objects.sort(键=拉姆达TUP:TUP [0])按行号#sort 返回list_objects
解决方案
修改
temp_object =数据集(temp_line_num,temp_data)
到
temp_object =数据集(temp_line_num,temp_data [:])
或
temp_object =数据集(temp_line_num,列表(temp_data))
通过传递 temp_data code>到
的DataSet
你没有创建列表的副本,你只要再利用现有之一。通过使用 [:]
或的list()
创建一个副本,而不是
In my function, I am creating unique variables that I want to add to a list. But whenever I append the next variable, the values of all the other variables inside the list change to the new one.
Here's my code:
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
解决方案
Change
temp_object = DataSet(temp_line_num, temp_data)
to
temp_object = DataSet(temp_line_num, temp_data[:])
or
temp_object = DataSet(temp_line_num, list(temp_data))
By passing temp_data
to the DataSet
you do not create a copy of the list, you just re-use the existing one. By using [:]
or list()
you create a copy instead.
这篇关于为什么我的列表的.append()改变每一个成员变量的值到新的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文