1

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
  • these list are of irregular length? What do you want to do with indexes that are not there in some lists? Commented Aug 13, 2015 at 1:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.