为什么我的列表的 .append() 将每个成员变量的值更改为新变量? [英] Why is my list's .append() changing the value of every member variable to the new variable?

查看:23
本文介绍了为什么我的列表的 .append() 将每个成员变量的值更改为新变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的函数中,我正在创建要添加到列表中的唯一变量.但是每当我追加下一个变量时,列表中所有其他变量的值都会更改为新的.

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.

这是我的代码:

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(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(),您可以创建一个副本.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆