Lambda And Filter In Python
Solution 1:
You can use a generator expression instead of filter
>>> ''.join(i for i in garbled if i != 'X')
'I am another secret message!'
If you wanted to use filter
you'd have to change your lambda
to
>>> ''.join(filter(lambda x: x != 'X', garbled))
'I am another secret message!'
Solution 2:
filter(function, iterable)
does the following procedure:
- Go through the elements in
iterable
(i.e. the second parameter) one at a time. - For each one of those elements, call
function
(i.e. the second parameter) on that element and see whether it returns true. - Collect together only those elements where the
function
returned true, and return a new list of those.
Look at what happens in step 2 if you pass lambda x: garbled.remove(x) if x == "X"
for the function
parameter: filter()
says to itself, "Hmm, if I set x="I"
then is garbled.remove(x) if x == "X"
true?". It's like you're shouting an instruction at filter()
in its second parameter: "hey, please remove all the "X"
s". But that's just not the right thing to go there. The requirements are very precise: it must be a function that takes an element and returns a true or false value.
Solution 3:
Cory already fixed your filter
.
In my opinion, your problem is handled best by a simple str.replace
.
>>>garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX">>>garbled.replace('X', '')
'I am another secret message!'
Solution 4:
message = filter(lambda x: garbled.remove(x) if x == "X", garbled)
This code doesn't work, because lambda function must be expression.
garbled.remove(x) if x == "X"
This is statement, not a expression. I delete if x=="X" to make an valid expression,
message = filter(lambda x: garbled.remove(x), garbled)
Next, I catch the error "'str' object has no attribute 'remove'". Because type of garbled is string, and there is no attribute that named 'remove' in string type. To use filter function, first argument must be 'predicate' function (that return True or False), and second argument must be iterable-like. OP's second solution satisfies this condition. second argument is string that is iterable (a list of characters), and first argument is a predicate function that takes one character that is supplied from the second argument string)
Solution 5:
You can do it this way. You have a mistake in lambda-condition. You even do not need string.replace()
.
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
f = lambda x: "" if x in "X"else x
message = filter(f, garbled)
"".join(message)
Post a Comment for "Lambda And Filter In Python"