How to export a list with different size from pyth

2019-08-14 05:04发布

问题:

I already read Export a Python List to Excel and How to export user inputs (from python) to excel worksheet, but the different is that my list is in more than one size. I mean my list is something like this:

List=[[list1],[list2],...,[list10]]

list1, list2,...,list10 are including of 3 numbers with float46 formats. For example:

list1=[1.34543324545676,2.4354356645454,2.786434355455]
list2=[3.33434342343423,6.6566665655655,7.343545454545]

...

list10=[3.6565656565465,7.45454536565656,7.56565656565]

I want to export the List to an Excel file that list1 is in the first column, list2 is in the second column, ..., list10 is in the tenth column.

回答1:

If you are fine with using csv module to write to a csv, and then open it up in excel, then you can use csv module along with zip() , to write out your list of lists as columns. Example -

import csv
with open('<excel file>','w') as f:
    writer = csv.writer(f)
    #writer.writerow([<header row>]) #uncomment this and put header, if you want header row , if not leave it commented.
    for x in zip(*list_of_lists):
        writer.writerow(x)

The *list_of_list unpacks the lists and sends each inner list as a separate argument to zip() and zip() combines each list at each index so first list output of zip() is the 0th index of all lists, etc. So this basically transposes the list of lists.


Example/Demo -

>>> import csv
>>> ll = [[1,2,3],[3,4,5],[4,2,1]]
>>> with open('a.csv','w') as f:
...     writer = csv.writer(f)
...     for x in zip(*ll):
...         writer.writerow(x)
...

Output in a.csv is -

1,3,4

2,4,2

3,5,1

I think something similar (using zip() ) can be done for other excel libraries as well, if you want.



回答2:

Here is one way to do it using the XlsxWriter module that will automatically handle different list lengths:

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()

list1 = [1.34543324545676, 2.4354356645454, 2.786434355455]
list2 = [3.33434342343423, 6.6566665655655, 7.343545454545]
list3 = [3.6565656565465,  7.45454536565656, 7.56565656565]         

List  = [list1, list2, list3]

row_num = 0

for col_num, data in enumerate(List):
    worksheet.write_column(row_num, col_num, data)

workbook.close()

Output: