写一个列表来优化

我正在尝试执行以下操作:

对于列A中的每个条目,如果该条目在同一列A中重复出现,则将列E中的所有值加在一起。

然后,只把Col E的那个(增加的)值写入另一个excel表格。 每个Col A条目应具有与其相对应的所有Col E值。

但是,我只能为最后一行创build输出表。

源Excel工作表

这是我写的代码,

#! /usr/bin/env python from xlrd import open_workbook from tempfile import TemporaryFile from xlwt import Workbook wb = open_workbook('/Users/dem/Documents/test.xlsx') wk = wb.sheet_by_index(0) for i in range(wk.nrows): a = str(wk.cell(i,0).value) b = [] e = [] for j in range(wk.nrows): c = str(wk.cell(j,0).value) d = str(wk.cell(j,4).value) if a == c: b.append(d) print b e.append(b) book = Workbook() sheet1 = book.add_sheet('sheet1') n = 0 for n, item in enumerate(e): sheet1.write(n,0,item) n +=1 book.save('/Users/dem/Documents/res.xls') book.save(TemporaryFile()) 

犯错 在这里输入图像说明 生成表单(我的):

代码中的注释。

 #! /usr/bin/env python from xlrd import open_workbook from tempfile import TemporaryFile from xlwt import Workbook import copy wb = open_workbook('C:\\Temp\\test.xls') wk = wb.sheet_by_index(0) # you need to put e=[] outside the loop in case they are reset to empty list every loop # e is used to store final result e = [] # f is used to store value in Col A which means we only record value once f = [] for i in range(wk.nrows): b = [] temp = None a = str(wk.cell(i,0).value) #here we only record value once if a in f: continue #here you should start from i+1 to avoid double counting for j in range(i+1, wk.nrows): c = str(wk.cell(j,0).value) if a == c: # you can put operations here in order to make sure they are executed only when needed d = str(wk.cell(j,4).value) k = str(wk.cell(i,4).value) f.append(a) # record all the value in Col E b.append(k) b.append(d) # you need to use deepcopy here in order to get accurate value temp = copy.deepcopy(b) # in your case, row 5 has no duplication, temp for row 5 will be none, we need to avoid adding none to final result if temp: e.append(temp) book = Workbook() sheet1 = book.add_sheet('sheet1') n = 0 for n, item in enumerate(e): sheet1.write(n,0,item) # you don't need n+=1 here, since n will increase itself book.save('C:\\Temp\\res.xls') book.save(TemporaryFile()) 

我想你应该期待用dialect='excel'来使用csv.writer在这个文档中有一个使用例子。 我认为这只是使用excel的最简单方法,如果你不需要像你的情况那样的巨大function。