gpt4 book ai didi

python - 用于替换字符串中字符的 Lambda 函数

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:36 24 4
gpt4 key购买 nike

下面是替换字符的Python代码。有人可以解释一下 lambda 部分吗?最初,X 取“p”并检查它是 a1 还是 a2。交换发生在哪里?


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)
print(newSent)
return ''.join(newSent)


print(replaceUsingMapAndLambda("puporials toinp", "p", "t"))

输出:

$python main.py
['t', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', ' ', 'p', 'o', 'i', 'n', 't']
tutorials point

谢谢,雷西卡

最佳答案

这等同于:

def replaceUsingMapAndLambda(sent, a1, a2):
# We create a lambda that only works if we input a1 or a2 and swaps them.
newSent = []
for x in sent:
if x != a1 and x != a2:
newSent.append(x)
elif x == a2:
newSent.append(a1)
else:
newSent.append(a2)

print(newSent)
return ''.join(newSent)

Lambda是创建匿名函数的关键字,map将此匿名函数应用于列表的每个元素并返回结果。

关于python - 用于替换字符串中字符的 Lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52513846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com