简体   繁体   English

将列表写入.xls文件的最“ pythonic”方式?

[英]Most 'pythonic' way to write list to .xls file?

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 . 我试图将列表转换为制表符允许的格式,以便可以写入.xls文件,但是我想出办法的唯一方法似乎很单调。 I was wondering if anyone knew a quicker, more efficient, and more 'pythonic' way of writing a list to an .xls 我想知道是否有人知道更快,更有效和更“ pythonic”的将列表写入.xls的方法

You can accomplish the formatting you're looking for with a list comprehension 您可以通过列表理解来完成所需的格式设置

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

See python's documentation on join . 请参阅python的join文档。

Use the built-in csv library. 使用内置的csv库。 http://docs.python.org/2/library/csv.html http://docs.python.org/2/library/csv.html

Assuming out_file is already opened, as in the commented out parts of your example: 假设out_file已经打开,如示例中注释掉的部分:

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

To be a bit pedantic, you're trying to write a tab-delimited file rather than actual Excel. 有点古怪,您尝试编写制表符分隔的文件,而不是实际的Excel。 Excel can handle tab-delimited files just fine, but if you need true Excel xlwt is the usual library. Excel可以很好地处理制表符分隔的文件,但是如果需要,Excel xlwt是常用的库。 Using it you'd have something like this: 使用它,您将得到以下内容:

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)

If you have to write to XLS, I would use the answers given here: 如果您必须写XLS,我将使用此处给出的答案:

Python - Write to Excel Spreadsheet Python-写入Excel电子表格

While using tab separated variables or csv will often work, expect failure if you need UTF-8. 虽然使用制表符分隔的变量或csv通常可以正常工作,但是如果您需要UTF-8,可能会失败。 You will not see the characters you expect once you get out of the ASCII range. 一旦超出ASCII范围,您将看不到期望的字符。

I have not tried the real Excel products mentioned in saxman01's references, but they might be more suitable if the target is really Excel. 我没有尝试过saxman01的参考文献中提到的真正的Excel产品,但是如果目标是真正的Excel,则它们可能更适合。 Will they handle other character sets? 他们会处理其他字符集吗? Just something to think about if you need to go international (or even domestic to non-English speaking audience). 如果您需要走向国际(甚至是面向非英语国家的听众),则可以考虑一下。

Then you could be asking yourself, what would Google Docs do? 然后您可能会问自己,Google文档会做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM