【问题标题】:how to convert a nested listed expression properly write into Excel如何将嵌套列出的表达式正确转换为 Excel
【发布时间】:2022-08-11 01:14:19
【问题描述】:

我将某些数据点(其中一些是类对象)存储在列表表达式中。然后我想将其转换为适当的形式以写入 csv 文件。

#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()

由于我没有正确执行i[2] 操作,我得到<generator object <listcomp>.<genexpr> at 0x0000024869479660>。我想知道如何解决这个问题并在 Excel 工作表中获取以下内容。

  • 为什么你在第二个元组上有destinationNode
  • @Yuca 那是一个错字。解决它

标签: python pandas list


【解决方案1】:

括号以您不怀疑的方式起作用(创建生成器对象) 所以这样做

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

应该这样做

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2017-11-28
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多