condensed syntax?

Eric Brunel eric.brunel at pragmadev.com
Tue Jul 30 06:38:18 EDT 2002


<posted & mailed>

Matthieu Bec wrote:

> is there any way to condense the following:
> 
>       # scan subdir(s) within mydir
>       for d in os.listdir(mydir):
>          dd=os.path.join(mydir,d)
>          if os.path.isdir(dd):
>             self.subdir.append(dd)
> 
> 
> what follows doesn't work, but I'm thinking of a something like:
> 
>         self.subdir=[(os.path.isdir(dd=os.path.join(mydir,d))?dd:pass)
> for d in
> os.listdir(mydir) ]

Try (untested):

self.subdir = [os.path.join(mydir, d) for d in os.listdir(mydir)
                 if os.path.isdir(os.path.join(mydir, d))]

You won't be able to make an assignment (like to your dd variable) in a 
list comprehension (except by utterly horrible and unreadable ways...), 
hence the double os.path.join...

You may also do:

self.subdir = filter(os.path.isdir,
               [os.path.join(mydir, d) for d in os.listdir(mydir)])

Maybe a tad more readable, but probably less efficient too...

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list