web2py追加要列出的字典

时间:2014-09-03 08:52:31

标签: list dictionary web2py

我从excel创建一个词典列表。代码如下所示。会发生什么是列表包含所有行的最后一行excel值。我试过python shell。它工作正常。为什么所有行都使用最后一行值更新?

d = {}
l = []
up = os.path.join(request.folder,'uploads')
workbook = xlrd.open_workbook(os.path.join(request.folder,'uploads','meas.xls'))
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    #print 'Row:', curr_row
    curr_cell = -1
    while curr_cell < num_cells:
        curr_cell += 1
        # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
        cell_type = worksheet.cell_type(curr_row, curr_cell)
        cell_value = worksheet.cell_value(curr_row, curr_cell)
        #print '    ', cell_type, ':', cell_value
        if curr_cell == 0:
            d['loc_of_work'] = cell_value
        if curr_cell == 1:
            d['n'] = cell_value
        if curr_cell == 2:
            d['t'] = cell_value
        if curr_cell == 3:
            d['l'] = cell_value
        if curr_cell == 4:
            d['b'] = cell_value
        if curr_cell == 5:
            d['d'] = cell_value
    print 'dict'
    print d.items()
    l.append(d)
    print 'len of list:'
    print len(l)
    print 'list:'
    for i,j in enumerate(l):
        print i,j

1 个答案:

答案 0 :(得分:0)

问题是你在while循环之外声明d,这意味着在循环中你只是在每次迭代时用新值覆盖相同的dict。您的列表只包含对同一个dict对象的多个引用,该对象包含最后一行的值,因为这些是要写入dict的最后一个值(所有以前的值都被覆盖)

moveoing:

d = {}
第一个while循环中的

应该解决你的问题