lambda和python中的过滤器 [英] lambda and filter in python
问题描述
我有以下字符串,我想通过过滤X来解码
I have the following string and I wanna decode by filtering the X's
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
我想过滤.我尝试了以下代码
And I would like to filter. I tried the following code
message = filter(lambda x: garbled.remove(x) if x == "X", garbled)
我没有通过这种方式工作.我找到了其他解决方案:
I did not make this way work. I have found this other solution:
message = filter(lambda x: x != "X", garbled)
但是我仍然想知道为什么第一个不起作用.我可以解决它吗?
But I still wonder why did not work the first one. Can I fix it?
(我是python btw的新手),谢谢!
(I am new in python btw) thanks!
推荐答案
filter(function, iterable)
执行以下过程:
- 一次浏览一次
iterable
中的元素(即第二个参数). - 对于每个元素,请对该元素调用
function
(即第二个参数),看看它是否返回true. - 仅将
function
返回true的那些元素收集在一起,并返回这些元素的新列表.
- 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.
看看如果您为function
参数传递lambda x: garbled.remove(x) if x == "X"
会在步骤2中发生什么:filter()
对自己说:嗯,如果我设置了x="I"
,那么garbled.remove(x) if x == "X"
是真的吗?".就像您在filter()
的第二个参数中大喊大叫:嘿,请删除所有"X"
s".但这并不是去那里的正确选择.要求非常精确:它必须是一个接受元素并返回true或false值的函数.
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.
这篇关于lambda和python中的过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!