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:


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




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.


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):

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 -




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


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)