Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Map function และ Lambda expression ใน Python แทนที่ตัวอักษร

ต้องการแทนที่ตัวอักษร a1 ด้วย a2 และ a2 ด้วย a1 เช่น สำหรับสตริงอินพุท

"puporials toinp"

และตัวอักษร p และ t ต้องการผลลัพธ์เป็น

"tutorials point"

ใช้ map function และ lambda เพื่อแทนที่ map(lambda, input) วนลูปแต่ละรายการและนำ lambda ไปใช้

ตัวอย่าง

def replaceUsingMapAndLambda(sent, a1, a2):
    # สร้าง lambda ที่ทำงานก็ต่อเมื่ออินพุทเป็น a1 หรือ a2 และสลับกัน
    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