使用局部函数/中间变量提高pythons列表的可读性

使用局部函数/中间变量提高pythons列表的可读性,python,performance,list-comprehension,code-readability,Python,Performance,List Comprehension,Code Readability,我想对齐(这里是简单方程列表的左侧,当前为字符串)。基本示例如下: 414 / 46 = 9 3 / 1 = 3 114 / 38 = 3 给定代码将返回此对齐列表(在示例resp.“=”): 该列表可能会变大(通过有限的目标平台) 现在我破解了一个嵌套的列表理解表达式。 此代码中的两个表达式均有效。 但向其他程序员展示,我在可读性/代码效率方面遇到了一些“阻力”。我也喜欢创建其他(新鲜的和有经验的)程序员也能快速理解的代码。另一方面,这可能不会对目标系统造成太大压力 看着 及 提示人们,有时

我想对齐(这里是简单方程列表的左侧,当前为字符串)。基本示例如下:

414 / 46 = 9
3 / 1 = 3
114 / 38 = 3
给定代码将返回此对齐列表(在示例resp.“=”):

该列表可能会变大(通过有限的目标平台)

现在我破解了一个嵌套的列表理解表达式。 此代码中的两个表达式均有效。 但向其他程序员展示,我在可读性/代码效率方面遇到了一些“阻力”。我也喜欢创建其他(新鲜的和有经验的)程序员也能快速理解的代码。另一方面,这可能不会对目标系统造成太大压力

看着 及 提示人们,有时列表理解不是正确的工具

对l中的e使用普通循环
我看不出如何就地交换列表中的方程式stings

我可以将表达式转换为一些旧的c型索引循环
,用于xrange中的I
循环,将新的(修剪过的)lexpr方程简单地分配给给定的索引

我想更好地了解在哪里使用哪些选项(可能还有原因)? 在这两个方面:理解他人代码和性能

我自己尝试了这两种变体(注释行):


我建议使用局部函数:

def trim_equations_lwidth( equation_list, width ):
  '''expects string-expressions like "1 + 3 = x" 
  and trims all of the left expr to same width. 
  Expects width to be >= length of lexp
  '''

  def _replace(equation):
     lexpr = equation[:equation.find('=')]
     return equation.replace(lexpr, lexpr.rjust(width, ' '))

  ltrimmed_equations = [_replace(equation) for equation in equation_list]

  return ltrimmed_equations

“改进”?“蟒蛇”?我从来没有见过或想象过这两个词能在同一句话中出现。当然不可能:-)哇,这个标题也可以这样读!我亲爱的英语:-)
def trim_equations_lwidth( equation_list, width ):
  '''expects string-expressions like "1 + 3 = x" 
  and trims all of the left expr to same width. 
  Expects width to be >= length of lexp
  '''
  #ltrimmed_equations = [ equation.replace( equation[:equation.find('=')], equation[:equation.find('=')].rjust(width, ' ')) for (equation) in equation_list ]
  ltrimmed_equations = [ equation.replace(lexpr, lexpr.rjust(width, ' ')) for (lexpr, equation) in ( ( equ[:equ.find('=')], equ)  for (equ) in equation_list )]

  return ltrimmed_equations
def trim_equations_lwidth( equation_list, width ):
  '''expects string-expressions like "1 + 3 = x" 
  and trims all of the left expr to same width. 
  Expects width to be >= length of lexp
  '''

  def _replace(equation):
     lexpr = equation[:equation.find('=')]
     return equation.replace(lexpr, lexpr.rjust(width, ' '))

  ltrimmed_equations = [_replace(equation) for equation in equation_list]

  return ltrimmed_equations