Reputation: 1378
Hi guys Im trying to write a code that uses a list of functions and a list of integers and only returns the ones that have at least 1 true in the list of functions like so:
tuple(lambda func,data:filter(lambda x:map(lambda y:y(x)==true,func),data))
func=(lambda x: x>3,lambda x: x%2==0)
data=(1,2,3,4,5,6,7,8,9,10)
so the list should return 4,6,8,10 but instead it returns the entire list,does anybody knows why?
P.S I know it can be done very easily in a different way, but Its a lambda exercise.
Upvotes: 0
Views: 39
Reputation: 95957
You can use an expression like the following:
tuple(filter(lambda x: any(filter(lambda f: f(x), func)), data))
So,
In [17]: func=(lambda x: x>3,lambda x: x%2==0)
...: data=(1,2,3,4,5,6,7,8,9,10)
...:
...:
In [18]: tuple(filter(lambda x: any(filter(lambda f: f(x), func)), data))
Out[18]: (2, 4, 5, 6, 7, 8, 9, 10)
Also note, your expression raises a TypeError
, so I don't know what you mean about it returning the whole list.
It would probably be more readable to use something like:
In [23]: tuple(
...: x for x in data
...: if any(f(x) for f in func)
...: )
Out[23]: (2, 4, 5, 6, 7, 8, 9, 10)
Or without any
(a ridiculous constraint)
In [29]: tuple(filter(lambda x: tuple(filter(None, map(lambda f: f(x), func))), data))
Out[29]: (2, 4, 5, 6, 7, 8, 9, 10)
Upvotes: 1
Reputation: 50185
It's more Pythonic to map these functions using list comprehensions:
data = range(1, 11)
funcs = (lambda x: x > 3, lambda x: x % 2 == 0)
new_data = [x for x in l if all(f(x) for f in funcs)]
# new_data == [4, 6, 8, 10]
Upvotes: 0