Lambda funkce

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Jednoduché funkce

def average(values):
    average_value = sum(values) / len(values)
    return average_value
Intermediate Python for Developers

Lambda funkce

  • Klíčové slovo lambda
    • Představuje anonymní funkci

 

lambda
Intermediate Python for Developers

Lambda funkce

  • Klíčové slovo lambda
    • Představuje anonymní funkci

 

lambda arguments
Intermediate Python for Developers

Lambda funkce

  • Klíčové slovo lambda
    • Představuje anonymní funkci

 

lambda arguments:
Intermediate Python for Developers

Lambda funkce

  • Klíčové slovo lambda
    • Představuje anonymní funkci

$$

lambda arguments: expression
  • Konvencí je používat x pro jediný argument
  • expression odpovídá tělu funkce
  • Příkaz return není vyžadován

$$

  • Lze uložit jako proměnnou
Intermediate Python for Developers

Vytvoření lambda funkce

# Lambda average function
print(lambda x: sum(x) / len(x))



<function <lambda> at 0x7f11ab813d80>
# Custom average function
def average(x):
    return sum(x) / len(x)  

print(average)
<function average at 0x7f11ab813ec0>
Intermediate Python for Developers

Použití lambda funkcí

# Get the average
(lambda x: sum(x) / len(x))
Intermediate Python for Developers

Použití lambda funkcí

# Get the average
(lambda x: sum(x) / len(x))([3, 6, 9])

$$

$$

# Print the average
print((lambda x: sum(x) / len(x))([3, 6, 9]))
6.0
Intermediate Python for Developers

Uložení a volání lambda funkce

# Store lambda function as a variable
average = lambda x: sum(x) / len(x)

# Call the average function print(average([3, 6, 9]))
6.0
Intermediate Python for Developers

Více parametrů

# Lambda function with two arguments
power = lambda x, y: x**y


# Raise 2 to the power of 3 print(power(2, 3))
8
Intermediate Python for Developers

Lambda funkce s iterovatelnými objekty

  • map() aplikuje funkci na všechny prvky iterovatelného objektu
names = ["john", "sally", "leah"]

# Apply a lambda function inside map() capitalize = map(lambda x: x.capitalize(), names)
print(capitalize)
<map object at 0x7fb200529c10>
# Convert to a list
print(list(capitalize))
['John', 'Sally', 'Leah']
Intermediate Python for Developers

Vlastní vs. lambda funkce

Scénář Typ funkce
Složitý úkol Vlastní
Opakovaný úkol Vlastní
Jednorázové použití Lambda
Jednoduchý úkol Lambda
Intermediate Python for Developers

Pojďme si procvičit!

Intermediate Python for Developers

Preparing Video For Download...