user7970547
user7970547

Reputation: 147

Python output in Excel

Trying to get the output of the cartesian product in excel using xlsxwriter and arrange them column-wise but have not been successful.

Intended Result:

If the first output is (A,B,C,D,E) the output should be displayed in excel in the following manner:

Row 0, Col 0 = A

Row 0, Col 1 = B

Row 0, Col 2 = C

Row 0, Col 3 = D

Row 0, Col 4 = E

then row+=1 and the next set of results are displayed in the same manner.

Code:

list1 = ['A', 'B', 'C', 'D', 'E', 'F']
list2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I']
list3 = ['A', 'B', 'C', 'D', 'E']
list4 = ['A', 'B', 'C', 'D']
list5 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I','J','K','L','M']

list = [(p,q,r,s,t) for p in list1 for q in list2 for r in list3 for s in 
        list4 for t in list5]

x = print(list)

import xlsxwriter
workbook = xlsxwriter.workbook('Stat.xlsx')
worksheet = workbook.add_worksheet()

row = 0
col = 0

for Apple, Boy, Cat, Dog, Eagle in (x):
  worksheet.write (row, col, Apple)
  worksheet.write(row, col + 1, Boy)
  worksheet.write(row, col + 1, Cat)
  worksheet.write(row, col + 1, Dog)
  worksheet.write(row, col + 1, Eagle)
  row += 1
workbook.close()

Upvotes: 1

Views: 1906

Answers (1)

Dan
Dan

Reputation: 45752

Does this do what you want?

list1 = ['A', 'B', 'C', 'D', 'E', 'F']
list2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I']
list3 = ['A', 'B', 'C', 'D', 'E']
list4 = ['A', 'B', 'C', 'D']
list5 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I','J','K','L','M']

# You probably could use product from itertools for this: https://docs.python.org/2/library/itertools.html#itertools.product
list_combined = [(p,q,r,s,t) for p in list1 
                             for q in list2 
                             for r in list3 
                             for s in list4 
                             for t in list5]

import xlsxwriter
workbook = xlsxwriter.Workbook('Stat.xlsx')
worksheet = workbook.add_worksheet()

for row, group in enumerate(list_combined):
    for col in range(5):
        worksheet.write (row, col, group[col])
workbook.close()

Upvotes: 2

Related Questions