write a loopin one line; process file paths

Xah Lee xah at xahlee.org
Wed Oct 19 01:33:18 EDT 2005


Thanks. Here's how the inner loop should be:

imgPaths2=map(lambda x: (x, re.sub( r"^(.+?)-s(\.[^.]+)$",r"\1\2", x)),
imgPaths)

though, now i just need something like

map( lambda x: os.path.exists(s)? x[1]:x[0],impPaths2)

but Pyhton doesn't support the
test ? trueResult : falseResult
construct.

(the semantic of this construct, of a conditional that RETURNS A
EXPRESSION, all in one line, is important in functional programing.
Perl supports it. In Mathematica, it's simply the form If[testExpr,
trueExpr, falseExpr]. In lisp, similar: (if testExpr trueExpr
falseExpr) )

is there a way to similate it?

 Xah
 xah at xahlee.orghttp://xahlee.org/

bonono at gmail.com wrote:
> what do you mean by one line ? Using map/filter, I believe it is
> possible.
>
> Somthing like:
>
> map(lambda (s,f): os.path.exists(f) and f or s,
>     map(lambda x: (x, re.replace(x, "-s","")), imgPaths)
>
> My regex is a bit rusty but I hope you got the idea of what I am trying
> to do. If there is a way to make the re return without destroying x,
> the outer map is not needed I believe(that is run it twice, once for
> getting the filename to do the testing, then again based on the testing
> result).
>




More information about the Python-list mailing list