简体   繁体   English

为什么列表的.append()将每个成员变量的值更改为新变量?

[英]Why is my list's .append() changing the value of every member variable to the new variable?

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. 通过将temp_data传递到DataSet您无需创建列表的副本,而只需重用现有的副本即可。 By using [:] or list() you create a copy instead. 通过使用[:]list()可以创建一个副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM