Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert a nested listed expression properly write into Excel

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading