filter with dynamic value
Mikael Olofsson
mikael at isy.liu.se
Fri Sep 14 09:38:30 EDT 2001
On 14-Sep-2001 Achim Domma wrote:
> I have something like this:
>
> ids = [(1,'abc'),(2,'abc'),(3,'xyz'),(4,'xyz')]
> comp = 'xyz'
>
> now I want to use filter to remove all items from ids which don't have
> 'xyz'
> as second value. I think the following should work:
>
> filter(lambda x: x[1]=='xyz')
>
> but how can I do this with an dynamic value ? If I try the following I get
> problems with the scope of comp :
>
> filter(lamdba x: x[1]==comp)
>
> I think this can't be to complicated, but it seems that my C++ trained
> brain hides once again the solution from me ...
First of all, you need to provide the original list ids. Try the following.
filter(lambda x: x[1]=='xyz', ids)
Second, you misspelled lambda in your second filter. If comp is global,
you can do the following
filter(lambda x: x[1]==comp, ids)
But if comp is local, the following should do:
filter(lambda x, comp=comp: x[1]==comp, ids)
HTH
/Mikael
-----------------------------------------------------------------------
E-Mail: Mikael Olofsson <mikael at isy.liu.se>
WWW: http://www.dtr.isy.liu.se/dtr/staff/mikael
Phone: +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
Date: 14-Sep-2001
Time: 15:29:28
/"\
\ / ASCII Ribbon Campaign
X Against HTML Mail
/ \
This message was sent by XF-Mail.
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com
More information about the Python-list
mailing list