Remove items from a list

William Park opengeometry at yahoo.ca
Wed Sep 8 02:11:07 EDT 2004


Paul McGuire <ptmcg at austin.rr._bogus_.com> wrote:
> "Stan Cook" <scook at elp.rr.com> wrote in message
> news:yWv%c.33126$Dl4.19812 at fe2.texas.rr.com...
> > Yes, I used the listdir.  The list is a list of files in the
> > directory.  I want to filter everything out but the ".dbf"
> > files.
> >
> 
> You said the answer yourself - "I want to _filter_ everything out but
> the ".dbf" files."
> 
> Use filter built-in, and use str's endswith() method in place of [-4:]
> list slicing.
> 
> dirlist = [ "a.txt", "b.txt", "c.dbf", "d.txt", "e.dbf" ]
> isdbf = lambda x : x.endswith(".dbf")
> print filter( isdbf, dirlist )
> 
> gives:
> 
> ['c.dbf', 'e.dbf']

Off topic... but if OP is interested in shell solution comparable to
above, then there are two I can offer:

    dirlist=( a.txt b.txt c.dbf d.txt e.dbf )

    1.  echo ${dirlist[*]|/*.dbf}

    2.  func () {
	    [[ $1 == *.dbf ]]
	}
	arrayfilter func dirlist

    3.	for i in ${dirlist[*]}; do
	    [[ $1 == *.dbf ]] && echo $i
	done

The first is shell version of Python's list comprehension, the second is
shell version of Python's filter(), and the third is standard loop
solution.

Ref:
    http://freshmeat.net/projects/bashdiff/
    help '${var|'
    help arrayfilter

-- 
William Park <opengeometry at yahoo.ca>
Open Geometry Consulting, Toronto, Canada



More information about the Python-list mailing list