Python 中的對映函式和 Lambda 表示式來替換字元


我們想用字元 a1 替換字元 a2,用 a2 替換 a1。例如,

對於輸入字串,

"puporials toinp"

以及字元 p 和 t,我們將結束字串希望如下所示 −

"tutorials point"

為此,我們可以使用對映函式和 lambda 表示式來進行替換。 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"))

輸出

這將提供以下輸出 −

tutorials point

更新時間:20-6 月 -2020

496 次瀏覽

開啟你的 職業道路

完成課程獲得認證

開始吧
廣告
© . All rights reserved.