write a loopin one line; process file paths

bonono at gmail.com bonono at gmail.com
Wed Oct 19 06:32:37 CEST 2005

what do you mean by one line ? Using map/filter, I believe it is

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

Xah Lee wrote:
> is there a way to condense the following loop into one line?
> # -*- coding: utf-8 -*-
> # python
> import re, os.path
> imgPaths=[u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2059m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2062m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2097m-s.jpg',
> u'/Users/t/web/Periodic_dosage_dir/lanci/t4/oh/DSCN2099m-s.jpg',
> u'/Users/t/web/Icons_dir/icon_sum.gif']
> # change the image path to the full sized image, if it exists
> # that is, if image ends in -s.jpg, find one without the '-s'.
> temp=imgPaths[:]
> imgPaths=[]
> for myPath in temp:
>     p=myPath
>     (dirName, fileName) = os.path.split(myPath)
>     (fileBaseName, fileExtension)=os.path.splitext(fileName)
>     if(re.search(r'-s$',fileBaseName,re.U)):
>         p2=os.path.join(dirName,fileBaseName[0:-2]) + fileExtension
>         if os.path.exists(p2): p=p2
>     imgPaths.append(p)
> temp=[]
> print imgPaths
>  Xah
>  xah at xahlee.org

More information about the Python-list mailing list