converting boolean filter function to lambda
Ian Kelly
ian.g.kelly at gmail.com
Thu Jun 25 12:09:53 EDT 2015
On Thu, Jun 25, 2015 at 9:59 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> I have the following function:
>
> def phone_found(p):
> for c in contacts:
> if p in c:
> return True
> return False
>
> with the following test data:
>
> contacts = ['672.891.7280 x999', '291.792.9000 x111']
> main = ['291.792.9001', '291.792.9000']
>
> which works:
>
> filter(phone_found, main)
> # ['291.792.9000']
>
> My attempt at a lambda function fails:
>
> filter(lambda p: (p in c for c in contacts), main)
> # ['291.792.9001', '291.792.9000']
>
> Besides using a lambda ;) , what have I done wrong?
The lambda returns a generator, not a boolean. All generators are truthy.
I think you want this instead:
filter(lambda p: any(p in c for c in contacts), main)
More information about the Python-list
mailing list