Python ฟังก์ชันแลมบ์ดาพร้อมตัวอย่าง

⚡ สรุปอย่างชาญฉลาด

Lambda functions in Python are small anonymous functions defined with the lambda keyword instead of def. They hold a single expression, take any number of arguments, and are often passed directly to built-ins such as map(), filter(), and sorted().

  • 🔑 Lambda keyword: A lambda is written as lambda arguments: expression, with no def, no name, and no explicit return statement.
  • 🧮 Single expression: The body holds exactly one expression whose value is returned automatically, so statements and multiple lines are not allowed.
  • 🔗 Built-in pairing: Lambdas are commonly passed to map(), filter(), reduce(), and sorted() to transform or select items in a sequence.
  • IIFE: A lambda can be defined and called immediately using the pattern (lambda x: x + x)(2), returning a result at once.
  • 🇧🇷 Versus def: Regular functions need a name and can hold many statements, while lambdas trade that power for compact, one-line syntax.
  • 🤖 ความช่วยเหลือจากเอไอ: AI assistants such as GitHub Copilot generate lambda expressions for map, filter, and sort keys from a short prompt.

Python ฟังก์ชั่นแลมบ์ดา

ฟังก์ชั่นแลมบ์ดาคืออะไร Python?

A ฟังก์ชันแลมบ์ดาใน Python การเขียนโปรแกรมเป็นฟังก์ชันที่ไม่ระบุชื่อหรือฟังก์ชันที่ไม่มีชื่อ เป็นฟังก์ชันขนาดเล็กและจำกัดไม่ให้มีมากกว่าหนึ่งบรรทัด เช่นเดียวกับฟังก์ชันปกติ ฟังก์ชัน Lambda สามารถมีอาร์กิวเมนต์ได้หลายรายการด้วยนิพจน์เดียว

In Pythonนิพจน์แลมบ์ดา (หรือรูปแบบแลมบ์ดา) ถูกนำมาใช้เพื่อสร้างฟังก์ชันที่ไม่ระบุชื่อ โดยคุณจะใช้ไฟล์ แลมบ์ดา คำหลัก (เช่นเดียวกับที่คุณใช้ def เพื่อกำหนดฟังก์ชันปกติ) ทุกฟังก์ชันที่ไม่ระบุตัวตนที่คุณกำหนด Python จะมีส่วนสำคัญ 3 ส่วน คือ

  • คำหลักแลมบ์ดา
  • พารามิเตอร์ (หรือตัวแปรที่ถูกผูกไว้) และ
  • ฟังก์ชั่นร่างกาย

ฟังก์ชัน lambda สามารถมีพารามิเตอร์จำนวนเท่าใดก็ได้ แต่ตัวฟังก์ชันจะมีได้เพียงพารามิเตอร์เท่านั้น หนึ่ง การแสดงออก. นอกจากนี้ lambda ยังเขียนด้วยโค้ดบรรทัดเดียวและสามารถเรียกใช้ได้ทันที คุณจะเห็นการทำงานทั้งหมดนี้ในตัวอย่างที่กำลังจะมาถึง

ไวยากรณ์และตัวอย่าง

ไวยากรณ์อย่างเป็นทางการในการเขียนฟังก์ชันแลมบ์ดามีดังต่อไปนี้:

lambda p1, p2: expression

ในที่นี้ p1 และ p2 คือพารามิเตอร์ที่ส่งผ่านไปยังฟังก์ชันแลมบ์ดา คุณสามารถเพิ่มพารามิเตอร์ได้มากหรือน้อยตามที่คุณต้องการ

However, notice that we do not use brackets around the parameters as we do with regular functions. The last part (expression) is any valid Python expression that operates on the parameters you provide to the function.

1 ตัวอย่าง

ตอนนี้คุณรู้เกี่ยวกับแลมบ์ดาแล้ว เรามาลองดูตัวอย่างกัน ดังนั้นเปิดของคุณ IDLE และพิมพ์ตามนี้:

adder = lambda x, y: x + y
print (adder (1, 2))

Code คำอธิบาย

ที่นี่ เรากำหนดตัวแปรที่จะเก็บผลลัพธ์ที่ส่งคืนโดยฟังก์ชันแลมบ์ดา

1. คีย์เวิร์ด lambda ที่ใช้กำหนดฟังก์ชันที่ไม่ระบุชื่อ

2. x และ y คือพารามิเตอร์ที่เราส่งผ่านไปยังฟังก์ชันแลมบ์ดา

3. นี่คือเนื้อความของฟังก์ชัน ซึ่งจะเพิ่มพารามิเตอร์ 2 ตัวที่เราส่งผ่าน โปรดสังเกตว่ามันเป็นนิพจน์เดียว คุณไม่สามารถเขียนหลายคำสั่งในเนื้อความของฟังก์ชันแลมบ์ดาได้

4. เราเรียกใช้ฟังก์ชันและพิมพ์ค่าที่ส่งคืน

2 ตัวอย่าง

That was a basic example to understand the fundamentals and syntax of lambda. Let us now try to print out a lambda and see the result. Again, open your IDLE และพิมพ์ตามนี้:

#What a lambda returns
string='some kind of a useless lambda'
print(lambda string : print(string))

ตอนนี้บันทึกไฟล์ของคุณแล้วกด F5 เพื่อเรียกใช้โปรแกรม นี่คือผลลัพธ์ที่คุณควรได้รับ

Output:

<function <lambda> at 0x00000185C3BF81E0>

What is happening here? Let us look at the code to understand further.

Code คำอธิบาย:

1. Here, we define a เชือก that you will pass as a parameter to the lambda.

2. We declare a lambda that calls a print statement and prints the result.

But why does the program not print the string we pass? This is because the lambda itself returns a function object. In this example, the lambda is not being ที่เรียกว่า by the print function but is simply การคืน the function object and the memory location where it is stored. That is what gets printed at the console.

3 ตัวอย่าง

อย่างไรก็ตาม หากคุณเขียนโปรแกรมในลักษณะนี้:

#What a lambda returns #2
x="some kind of a useless lambda"
(lambda x : print(x))(x)

And run it by hitting F5, you will see an output like this.

Output:

some kind of a useless lambda

Now, the lambda is being called, and the string we pass gets printed at the console. But what is that weird syntax, and why is the lambda definition covered in brackets? Let us understand that now.

Code คำอธิบาย:

1. Here is the same string we defined in the previous example.

2. In this part, we are defining a lambda and calling it immediately by passing the string as an argument. This is something called an IIFE, and you will learn more about it in the upcoming sections of this tutorial.

4 ตัวอย่าง

Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE และในไฟล์ใหม่ ให้พิมพ์ดังต่อไปนี้:

#A REGULAR FUNCTION
def guru( funct, *args ):
funct( *args )
def printer_one( arg ):
return print (arg)
def printer_two( arg ):
print(arg)
#CALL A REGULAR FUNCTION 
guru( printer_one, 'printer 1 REGULAR CALL' )
guru( printer_two, 'printer 2 REGULAR CALL \n' )
#CALL A REGULAR FUNCTION THRU A LAMBDA
guru(lambda: printer_one('printer 1 LAMBDA CALL'))
guru(lambda: printer_two('printer 2 LAMBDA CALL'))

Now, save the file and hit F5 to run the program. If you did not make any mistakes, the output should be something like this.

Output:

printer 1 REGULAR CALL

printer 2 REGULAR CALL

printer 1 LAMBDA CALL

printer 2 LAMBDA CALL

Code คำอธิบาย:

1. A function called guru that takes another function as the first parameter and any other arguments following it.

2. printer_one is a simple function which prints the parameter passed to it and returns it.

3. printer_two is similar to printer_one but without the return statement.

4. In this part, we are calling the guru function and passing the printer functions and a string as parameters.

5. This is the syntax to achieve the fourth step (i.e., calling the guru function) but using lambdas.

ในส่วนถัดไป คุณจะได้เรียนรู้วิธีใช้ฟังก์ชัน lambda ด้วย แผนที่(), ลด()และ กรอง() in Python.

การใช้แลมบ์ดาด้วย Python ในตัว

ฟังก์ชัน Lambda มอบวิธีการอันสง่างามและทรงพลังในการดำเนินการโดยใช้วิธีการในตัว Python- เป็นไปได้เนื่องจาก lambdas สามารถเรียกใช้ได้ทันทีและส่งผ่านเป็นอาร์กิวเมนต์ของฟังก์ชันเหล่านี้

IIFE เข้า Python แลมบ์ดา

IIFE ย่อมาจาก เรียกใช้ฟังก์ชันการดำเนินการทันที It means that a lambda function is callable as soon as it is defined. Let us understand this with an example; fire up your IDLE และพิมพ์ตามนี้:

 (lambda x: x + x)(2)

นี่คือคำอธิบายผลลัพธ์และโค้ด:

ความสามารถของแลมบ์ดาที่จะเรียกใช้ได้ทันทีทำให้คุณสามารถใช้มันภายในฟังก์ชันเช่น map() และ ลด () มันมีประโยชน์เพราะคุณอาจไม่ต้องการใช้ฟังก์ชันเหล่านี้อีก

แลมบ์ดาในตัวกรอง ()

ฟังก์ชั่นตัวกรองใช้เพื่อเลือกองค์ประกอบเฉพาะจากลำดับขององค์ประกอบ ลำดับสามารถเป็นตัววนซ้ำใดๆ เช่น รายการ เซต สิ่งอันดับ ฯลฯ

The elements which will be selected are based on some pre-defined constraint. It takes 2 parameters:

  • ฟังก์ชันที่กำหนดข้อจำกัดในการกรอง
  • ลำดับ (ตัววนซ้ำใดๆ เช่น รายการ สิ่งอันดับ ฯลฯ)

ตัวอย่างเช่น

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = filter (lambda x: x > 4, sequences) 
print(list(filtered_result))

นี่คือผลลัพธ์:

[10, 8, 7, 5, 11]

Code คำอธิบาย:

1. ในคำสั่งแรก เราจะกำหนดรายการที่เรียกว่าลำดับซึ่งประกอบด้วยตัวเลขบางตัว

2. ที่นี่ เราประกาศตัวแปรชื่อ filtered_result ซึ่งจะเก็บค่าที่กรองแล้วที่ส่งคืนโดยฟังก์ชัน filter()

3. ฟังก์ชันแลมบ์ดาที่ทำงานบนแต่ละองค์ประกอบของรายการและส่งกลับค่าจริงหากค่านั้นมากกว่า 4

4. พิมพ์ผลลัพธ์ที่ส่งคืนโดยฟังก์ชันตัวกรอง

แลมบ์ดาในแผนที่ ()

The map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters:

  1. A function that defines the operation to perform on the elements
  2. ลำดับหนึ่งหรือหลายลำดับ

ตัวอย่างเช่น นี่คือโปรแกรมที่พิมพ์ตัวเลขกำลังสองในรายการที่กำหนด:

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences) 
print(list(filtered_result))

Output:

 [100, 4, 64, 49, 25, 16, 9, 121, 0, 1]

Code คำอธิบาย:

1. Here, we define a list called sequences which contains some numbers.

2. We declare a variable called filtered_result which will store the mapped values.

3. A lambda function which runs on each element of the list and returns the square of that number.

4. Print the result returned by the map function.

แลมบ์ดาลด ()

ฟังก์ชัน reduce เช่น map() ใช้ในการดำเนินการกับทุกองค์ประกอบในลำดับ อย่างไรก็ตาม ฟังก์ชันนี้แตกต่างจาก map ตรงที่การทำงาน ต่อไปนี้คือขั้นตอนที่ฟังก์ชัน reduce() ปฏิบัติตามเพื่อคำนวณเอาต์พุต:

ขั้นตอน 1) ดำเนินการตามการดำเนินการที่กำหนดไว้กับ 2 องค์ประกอบแรกของลำดับ

ขั้นตอน 2) Save this result.

ขั้นตอน 3) ดำเนินการด้วยผลลัพธ์ที่บันทึกและองค์ประกอบถัดไปในลำดับ

ขั้นตอน 4) ทำซ้ำจนกว่าจะไม่มีองค์ประกอบเหลืออยู่

นอกจากนี้ยังใช้พารามิเตอร์สองตัวด้วย:

  1. ฟังก์ชั่นที่กำหนดการดำเนินการที่จะดำเนินการ
  2. ลำดับ (ตัววนซ้ำใดๆ เช่น รายการ สิ่งอันดับ ฯลฯ)

ตัวอย่างเช่น นี่คือโปรแกรมที่ส่งคืนผลคูณขององค์ประกอบทั้งหมดในรายการ:

from functools import reduce
sequences = [1,2,3,4,5]
product = reduce (lambda x, y: x*y, sequences)
print(product)

นี่คือผลลัพธ์:

120

Code คำอธิบาย:

1. Import reduce from the functools module.

2. Here, we define a list called sequences which contains some numbers.

3. We declare a variable called product which will store the reduced value.

4. A lambda function that runs on each element of the list. It will return the product of that number as per the previous result.

5. Print the result returned by the reduce function.

ทำไม (และทำไมไม่) ใช้ฟังก์ชันแลมบ์ดา?

ดังที่คุณจะเห็นในส่วนถัดไป lambdas จะได้รับการปฏิบัติเหมือนกับฟังก์ชันปกติในระดับล่าม ในทางหนึ่ง คุณสามารถพูดได้ว่า lambdas มีไวยากรณ์ขนาดกะทัดรัดสำหรับการเขียนฟังก์ชันซึ่งส่งคืนนิพจน์เดียว

However, you should know when it is a good idea to use lambdas and when to avoid them. In this section, you will learn some of the design principles used by Python developers when writing lambdas.

One of the most common use cases for lambdas is in functional programming, as Python รองรับกระบวนทัศน์ (หรือสไตล์) ของการเขียนโปรแกรมที่เรียกว่าการเขียนโปรแกรมเชิงฟังก์ชัน

It allows you to provide a function as a parameter to another function (for example, in map, filter, etc.). In such cases, using lambdas offers an elegant way to create a one-time function and pass it as the parameter.

เมื่อใดที่คุณไม่ควรใช้ Lambda

คุณไม่ควรเขียนฟังก์ชันแลมบ์ดาที่ซับซ้อนในสภาพแวดล้อมการผลิต เพราะจะทำให้ผู้เข้ารหัสที่ดูแลโค้ดของคุณถอดรหัสได้ยาก หากคุณพบว่าตัวเองกำลังสร้างนิพจน์บรรทัดเดียวที่ซับซ้อน การกำหนดฟังก์ชันที่เหมาะสมจะเป็นวิธีที่ดีกว่ามาก แนวทางปฏิบัติที่ดีที่สุดคือ คุณต้องจำไว้ว่าโค้ดที่เรียบง่ายนั้นดีกว่าโค้ดที่ซับซ้อนเสมอ

Lambdas กับฟังก์ชันปกติ

As previously stated, lambdas are just functions which do not have an identifier bound to them. In simpler words, they are functions with no names (hence, anonymous). Here is a table to illustrate the difference between lambdas and regular functions in Python.

แลมบ์ดาส ฟังก์ชั่นปกติ
ไวยากรณ์:

lambda x : x + x
ไวยากรณ์:

def (x) :
return x + x 
ฟังก์ชัน Lambda สามารถมีนิพจน์ในร่างกายได้เพียงนิพจน์เดียวเท่านั้น ฟังก์ชันปกติสามารถมีนิพจน์และคำสั่งได้หลายรายการในร่างกาย
Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. ฟังก์ชันปกติต้องมีชื่อและลายเซ็น
Lambdas ไม่มีคำสั่ง return เนื่องจากเนื้อหาจะถูกส่งคืนโดยอัตโนมัติ Functions which need to return a value should include a return statement.

อธิบายความแตกต่าง

ความแตกต่างหลักระหว่างแลมบ์ดาและฟังก์ชันปกติก็คือ ฟังก์ชันแลมบ์ดาจะประเมินเพียงนิพจน์เดียวและให้ผลลัพธ์เป็นวัตถุฟังก์ชัน ด้วยเหตุนี้ เราจึงสามารถตั้งชื่อผลลัพธ์ของฟังก์ชัน lambda และใช้ในโปรแกรมของเราได้เหมือนที่เราทำในตัวอย่างก่อนหน้านี้

ฟังก์ชันปกติสำหรับตัวอย่างข้างต้นจะมีลักษณะดังนี้:

def adder (x, y):
return x + y 
print (adder (1, 2))

ในที่นี้ เราต้องนิยาม a พร้อมชื่อ สำหรับฟังก์ชันซึ่ง รับคืน ผลลัพธ์เมื่อเรา โทรศัพท์ it. A lambda function does not contain a return statement because it will have only a single expression which is always returned by default. You do not even have to assign a lambda either, as it can be immediately invoked (see the previous section). As you will see, lambdas become particularly powerful when we use them with Pythonฟังก์ชันในตัวของ

อย่างไรก็ตาม คุณอาจยังคงสงสัยว่า lambdas แตกต่างจากฟังก์ชันที่ส่งคืนนิพจน์เดียวอย่างไร (เหมือนกับตัวอย่างข้างต้น) ในระดับล่ามไม่มีความแตกต่างกันมากนัก อาจฟังดูน่าประหลาดใจ แต่ฟังก์ชัน lambda ใดๆ ที่คุณกำหนดไว้ Python ล่ามจะถือเป็นฟังก์ชันปกติ

At the bytecode level, the two definitions are handled in the same way by the Python interpreter. Now, you cannot name a function แลมบ์ดา เพราะมันถูกสงวนไว้โดย Python, but any other function name will yield the same bytecode.

คำถามที่พบบ่อย

Yes. A lambda can use a conditional expression such as lambda x: ‘even’ if x % 2 == 0 else ‘odd’. It cannot hold a full if statement, because the body of a lambda must be a single expression rather than a block of statements.

Generally no. PEP 8 recommends using def when a function needs a name, because binding a lambda to a variable gives it a name yet loses the clearer traceback that def provides. Lambdas are best passed directly to functions such as sorted(), map(), or filter().

No. At the bytecode level Python treats a lambda and an equivalent def the same way, so there is no speed advantage. A lambda only saves a line of code; it does not execute faster than a named function doing identical work.

Yes. A lambda can read variables from the enclosing scope, forming a closure. Inside a loop, be careful: the lambda captures the variable itself, not its current value, so use a default argument like lambda x, n=n: x + n to freeze it.

Pass a lambda as the key argument to sorted() or list.sort(). For example, sorted(users, key=lambda u: u[‘age’]) orders items by age. The lambda tells Python which value to compare for each element, giving concise custom sorting without a separate named function.

Not directly, because an anonymous lambda has no name to reference. You can work around this by assigning the lambda to a variable and calling that name, but a normal def function is the clearer and recommended choice for recursion.

Lambdas power quick, inline transformations in AI and machine learning code. Data scientists pass them to pandas .apply(), map(), and filter() to clean or reshape data, and as key functions for sorting features, keeping preprocessing compact inside larger training pipelines.

GitHub Copilot suggests complete lambda expressions from a short comment or the surrounding code, including the correct parameters and expression for map(), filter(), or sorted() calls. It can also propose converting a verbose lambda into a clearer named function when readability matters.

สรุปโพสต์นี้ด้วย: