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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP