Python Lambda从字符串中删除单词
我一直在想为什么这不起作用:Python Lambda从字符串中删除单词,python,lambda,Python,Lambda,我一直在想为什么这不起作用: command = "What's the weather like in London?" words = ["in", "like"] command = command.replace("?", "").split('weather')[1].split(", ") command = ",".join(filter(l
command = "What's the weather like in London?"
words = ["in", "like"]
command = command.replace("?", "").split('weather')[1].split(", ")
command = ",".join(filter(lambda x: x not in words, command))
print(command)
输出:
就像在伦敦一样
我认为lambda函数没有达到我预期的效果,再多的调整也不能产生正确的结果。我只想提取“伦敦”这个词
有什么想法吗?只需将您的3d线条替换为:
command = command.replace("?", "").split('weather')[1].split() #remove ", " from split
结果将是“伦敦”
原因是您的.split(“,”)实际上并没有拆分文本,但它会将其保存为列表中的一个元素(在下一个命令中无法正确连接)只需将您的三维线替换为以下内容:
command = command.replace("?", "").split('weather')[1].split() #remove ", " from split
结果将是“伦敦”
原因是您的.split(“,”)实际上并没有拆分文本,而是将其保存为列表中的一个元素(在下一个命令中无法正确连接)如果拆分错误,下面是一种有效的方法:
command = "What's the weather like in London?"
command = "".join([x for x in command.replace("?", "").split('weather')[1].split(" ") if x not in ["in", "like"]])
print(command)
输出:
London
你把它分错了,这里有一个有效的方法:
command = "What's the weather like in London?"
command = "".join([x for x in command.replace("?", "").split('weather')[1].split(" ") if x not in ["in", "like"]])
print(command)
输出:
London
在将
命令
传递给过滤器
之前,请查看该命令的值,然后考虑调用过滤器
的每个步骤中x
的值。提示:lambda表达式很好,但没有过滤正确的iterable。前3行结果是:['like in London']
这就是您想要的吗?在将命令传递给过滤器之前,请先查看命令的值,然后思考x
在调用过滤器的每一步中的值。提示:lambda表达式很好,但您没有过滤正确的iterable。前3行结果是:['像在伦敦]
这就是你想要的吗?