Python中的Map函数和Lambda表达式来替换字符
我们想要将字符a1替换为字符a2,将a2替换为a1。例如,
对于输入字符串,
"puporials toinp"
以及字符p和t,我们希望结尾字符串看起来像-
"nhooo.com"
为此,我们可以使用map函数和lambdas进行替换。map(lambda,input)函数遍历传递给它的每个项目(以可迭代输入的形式),并将lambda表达式应用于该函数。所以我们可以如下使用它-
示例
def replaceUsingMapAndLambda(sent, a1, a2):
# We create a lambda that only works if we input a1 or a2 and swaps them.
newSent = map(lambda x: x if(x != a1 and x != a2) else a1 if x == a2 else a2, sent)
return ''.join(newSent)
print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))输出结果
这将给出输出-
nhooo.com