1
the_list = [['a','b','c'],['b','c','d'],['c','d','e']]
output = []
for k in the_list:
    output.append(str(k)[1:-1].replace(',',"\t").replace("'",'').replace(' ',''))

print output
#['a\tb\tc', 'b\tc\td', 'c\td\te']
#for line in output:
    #out_file.write(line + '\n')

I'm trying to get the list into tab-delmited format so i can write to an .xls file but the only way i could figure out how to do it seemed pretty monotonous . I was wondering if anyone knew a quicker, more efficient, and more 'pythonic' way of writing a list to an .xls

4

4 回答 4

1

您可以使用列表理解来完成您正在寻找的格式

output = ["\t".join(a) for a in the_list]

请参阅关于join的 python 文档。

于 2013-10-10T20:07:22.147 回答
1

使用内置csv库。http://docs.python.org/2/library/csv.html

假设out_file已经打开,如示例中注释掉的部分:

output_writer = csv.writer(out_file, delimiter="\t")
output_writer.writerows(the_list)

有点迂腐,您正在尝试编写一个制表符分隔的文件,而不是实际的 Excel。Excel 可以很好地处理制表符分隔的文件,但如果你需要真正的 Excelxlwt是常用的库。使用它你会有这样的东西:

wb = xlwt.Workbook()
ws = wb.add_sheet('sheet_name')
for rownum, sublist in enumerate(the_list):
    for colnum, value in enumerate(sublist):
        ws.write(rownum, colnum, value)
wb.save(out_file)
于 2013-10-10T20:08:22.357 回答
0

如果您必须写信给 XLS,我会使用此处给出的答案:

Python - 写入 Excel 电子表格

于 2013-10-10T20:11:25.277 回答
0

虽然使用制表符分隔的变量或 csv 通常会起作用,但如果您需要 UTF-8,预计会失败。一旦超出 ASCII 范围,您将看不到预期的字符。

我没有尝试过 saxman01 的参考资料中提到的真正的 Excel 产品,但如果目标真的是 Excel,它们可能更合适。他们会处理其他字符集吗?如果您需要走向国际(甚至是国内对非英语观众),请考虑一些事情。

然后你可能会问自己,Google Docs 会做什么?

于 2013-10-10T20:29:58.397 回答