python list.append搞砸了字典条目(每个索引中只添加了最后一个条目)

时间:2017-02-10 20:57:36

标签: python-2.7

我有这段代码,单独的字典看起来很好,但如果附加到列表,列表只显示最后一个条目

def readExcel(fInputFile="", sheetname=""):

    mywb = xlrd.open_workbook(vInputFile, on_demand=True)
    sheet_names = mywb.sheet_names()
    mysheet = mywb.sheet_by_name(sheet_names[0])
    for row_idx in range(1,mysheet.nrows):
        for col_idx in range(mysheet.ncols):
            cell = mysheet.cell(row_idx,col_idx)
            hdr = mysheet.cell(0,col_idx)
            init_list(myl,str(hdr.value),str(cell.value))
        if testmethod==NOLOAD:
            mpt_noload_execute(myl)
        else:
            myll.append(myl)
            print("myll after each row", myll[row_idx-1]['uname'])

    for j in range(len(myll)):
        print("myll after file reading", myll[j]['uname'])

==============================

执行和结果:

>python mpt_login_test_driver.py

('myll after each row', 'autotest01')
('myll after each row', 'autotest02')
('myll after each row', 'autotest03')
('myll after file reading', 'autotest03')   <=== error
('myll after file reading', 'autotest03')  <=== error
('myll after file reading', 'autotest03')

1 个答案:

答案 0 :(得分:1)

你需要为myl每次迭代使用一个新的字典。否则你只是修改同一个。例如

def readExcel(fInputFile="", sheetname=""):

    mywb = xlrd.open_workbook(vInputFile, on_demand=True)
    sheet_names = mywb.sheet_names()
    mysheet = mywb.sheet_by_name(sheet_names[0])
    for row_idx in range(1,mysheet.nrows):
        myl={}
        for col_idx in range(mysheet.ncols):
            cell = mysheet.cell(row_idx,col_idx)
            hdr = mysheet.cell(0,col_idx)
            init_list(myl,str(hdr.value),str(cell.value))
        if testmethod==NOLOAD:
            mpt_noload_execute(myl)
        else:
            myll.append(myl)
            print("myll after each row", myll[row_idx-1]['uname'])

    for j in range(len(myll)):
        print("myll after file reading", myll[j]['uname'])

现在myll会附加 new dict,而不仅仅是修改旧的。