2014-09-03 74 views
0

我創建了一個excel字典列表。代碼如下所示。該列表包含所有行的最後一行excel值。我在python shell中嘗試過。它工作正常。爲什麼所有行都使用最後一行值更新?web2py將字典附加到列表

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 

回答

0

的問題是您在while循環,這意味着你只是覆蓋與每個迭代的新值相同的字典內環路之外聲明d。您的清單隻包含相同的字典對象,其中包含從最後一排的值,因爲這些將被寫入字典(所有以前的值都將被覆蓋)的最後的值多次引用

moveoing:

d = {} 

第一次while循環應該修復您的問題