代码之家  ›  专栏  ›  技术社区  ›  Ramy

最后一步!(python调整)

  •  -1
  • Ramy  · 技术社区  · 14 年前

    我有这个密码:

            emailRows = []
            for rowTuple in listOfRows: #row loop
                emailLine = []
                for tup in rowTuple: #field loop
                    emailLine.append(str(tup).center(20))                
                emailRows.append('\t'.join([field.strip().center(20) for field in emailLine]))
            rows = '\n'.join(emailRows)
            emailBody = emailBody + rows
    

    到目前为止我已经改成了这个代码:

            emailRows = []
            for rowTuple in listOfRows: #row loop
                emailRows.append('\t'.join([field.strip().center(20) for field in [str(tup).center(20) for tup in rowTuple]]))
            rows = '\n'.join(emailRows)
            emailBody = emailBody + rows
    

    3 回复  |  直到 14 年前
        1
  •  1
  •   nmichaels    14 年前
    '\n'.join(('\t'.join([field.strip().center(20) for
        field in [str(tup).center(20) for
            tup in rowTuple]])) for rowTuple in listOfRows)
    

    哇,太模糊了。我希望cProfile说这家伙是个重击手。

        2
  •  1
  •   Gareth Rees    14 年前

    我不相信这个结果值得你这么做,但是如果你打算把你所有的 for generator expressions 而不是列表理解,以避免创建(然后扔掉)中间列表。

        3
  •  1
  •   seriyPS    14 年前

    你可以用 map() for x in seq :

    rows='\n'.join(map(lambda row: '\t'.join(map(lambda cell: str(cell).center(20), row)), listOfRows))
    

    你也可以试试 reduce() join() :

    def cell_format(cell):
        return str(cell).center(20)
    
    def row_format(res, cell):
        return res+'\t'+cell
    
    def rows_format(res, row):
        return res+'\n'+row
    
    rows=reduce(rows_format,
                map(lambda row: reduce(row_format, map(cell_format, row)),
                    listOfRows))