Home > database >  how to convert a nested listed expression properly write into Excel
how to convert a nested listed expression properly write into Excel

Time:08-11

I store certain data points, some of which are class objects, in a list expression. I would like then to convert this into a proper form to write into a csv file.

#This is a vanilla class for this example
class Direction:
    def __init__(self, _from, _to):
        self._from= _from
        self._to= _to

#I perform some operations 
def myMethod():
  ....
 
#Suppose I run my method and obtain the following list    
arr = [(Direction(_from="A", _to="B"), 2 , ['1','2']),
         (Direction(_from="C", _to="D"), 8 , ['1','2', '3', '4','5'])]

#Now, I try to convert this into a format in a way that I can use pandas to write into CSV

toExcel = [(i[0]._from, i[0]._to, i[1], (k for k in i[2])) for i in arr]
  
output= pd.ExcelWriter('mypath.xlsx'), engine='xlsxwriter')
toExcel.to_excel(output, sheet_name='my sheet', index=False)
output.save()

Since I am not doing the i[2] operation properly, I get <generator object <listcomp>.<genexpr> at 0x0000024869479660>. I was wondering how I can solve this issue and obtain the following in an Excel sheet.

enter image description here

CodePudding user response:

the parenthesis is acting in a way you don't expect (creating a generator object) so do this

toExcel = [(i[0]._from, i[0]._to, i[1], *[k for k in i[2]]) for i in arr]

that should do it

  • Related