I want to align (here it is the left side of simple equations list, currently of strings). Basic example would be this:
414 / 46 = 9
3 / 1 = 3
114 / 38 = 3
Given code will returns this aligned (in the example resp. "=") list:
414 / 46 = 9
3 / 1 = 3
114 / 38 = 3
The list could become large (by means of the limited target platform).
Now I hacked me a nested list comprehension expression. Both expressions in this code do work. But showing to other coders I experienced some "resistance" regarding readability / code efficiency. I like to create code that would be quickly understandable by other (the fresh and also the somewhat experienced) coders, too. And that would on the other hand possibly not strain the target system too much.
Looking at Intermediate variable in a list comprehension for simultaneous filtering and transformation and Most elegant way to modify elements of nested lists in place hints to the thought that sometimes list comprehensions are not the right tool.
Using plain loop for e in l
I don't see how to in-place exchange the equation stings in the list.
I could convert the expression into some old c-style index-loop for i in xrange
loop with plain old assignment of new (trimmed) lexpr equations to the given indexes.
I would like to better understand where to use which options (and maybe why)? In that two aspects: understanding others code and performance.
I tried myself this two variants (commented line):
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
I'd suggest using a local function:
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