for循环中的字符串连接非常慢

时间:2017-10-24 07:16:57

标签: python string loops

我正在尝试创建xml输出然后生成excel文件,在我的循环脚本上它正在处理数千个数据但是现在我有一百万个数据并且需要太长时间而且有时会挂断,我只是想知道我是否有办法在这里优化循环。

用法:

loop = 10000正常

循环> = 100000结果太慢且堆叠

class ExcelHyperlink:
  def __init__(self,sheetName,displayName):
    self.sheetName = sheetName.replace(" ","_")
    self.displayName = displayName
  def toCellString(self):
    sheet = escapeHTML(self.sheetName)
    display = escapeHTML(self.displayName)
    return '<Cell ss:StyleID="s63" ss:HRef="#%s!A1"><Data ss:Type="String">%s</Data></Cell>\n' % (sheet,display)    

def getCellString(value):
  if isinstance(value,ExcelHyperlink):
    return value.toCellString()
  else:
    return "<Cell><Data ss:Type=\"String\">%s</Data></Cell>\n" % (value)

loop = 10000
data = [{u'test': 0, u'a': 0, u'b': 0},{u'test': 1, u'a': 1, u'b': 1},{u'test': 2, u'a': 2, u'b': 2},{u'test': 3, u'a': 3, u'b': 3},{u'test': 4, u'a': 4, u'b': 4}] * loop

headers = ['test', 'a', 'b']


xml = '''<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"><WindowHeight>600</WindowHeight><WindowWidth>800</WindowWidth><WindowTopX>0</WindowTopX><WindowTopY>0</WindowTopY><ProtectStructure>False</ProtectStructure><ProtectWindows>False</ProtectWindows></ExcelWorkbook>
<Styles><Style ss:ID="Default" ss:Name="Normal"><Alignment ss:Vertical="Bottom"/><Borders/><Font/><Interior/><NumberFormat/><Protection/></Style><Style ss:ID="s21"><NumberFormat ss:Format="General Date"/></Style><Style ss:ID="s63" ss:Name="Hyperlink"><Font ss:Family="Arial" ss:Color="#0563C1" ss:Underline="Single"/></Style><Style ss:ID="s23"><Alignment ss:Horizontal="Left" ss:Vertical="Bottom"/><Font x:Family="Swiss" ss:Bold="1"/></Style></Styles>
'''

for row in data:  
  xml += "<Row>\n"
  for item in headers:    
    #xml += str(row)
    xml += getCellString(row[item])
  xml += "</Row>\n"
xml += '''</Table>                

<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Selected/>
<Panes></Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
'''
xml += "</Workbook>"

1 个答案:

答案 0 :(得分:2)

python中的字符串是不可变的。所有这些重复的字符串添加操作都是浪费,因为必须分配和创建新的内存和对象,并在每次迭代时复制数据。

我建议将所有内容放在列表中并在结尾处调用str.join

xml_artefacts = []
for row in data:  
    xml_artefacts.append("<Row>\n")
    for item in headers:    
        xml_artefacts.append(getCellString(row[item]))
    xml_artefacts.append("</Row>\n")

xml_artefacts.append('''</Table>  ...  </Workbook>''')

现在,使用xml字符串执行连接。

xml += ''.join(xml_artefacts)