map(), filter() si reduce()
Functia map()
Aplica o functie fiecarui element dintr-un iterabil:
map(functie, iterabil)
Exemple:
numere = [1, 2, 3, 4, 5]
# Patrate
patrate = list(map(lambda x: x**2, numere))
# [1, 4, 9, 16, 25]
# Cu functie definita
def dublu(x):
return x * 2
duble = list(map(dublu, numere))
# [2, 4, 6, 8, 10]
# Cu mai multe iterabile
a = [1, 2, 3]
b = [10, 20, 30]
sume = list(map(lambda x, y: x + y, a, b))
# [11, 22, 33]
Functia filter()
Filtreaza elementele care satisfac o conditie:
filter(functie, iterabil)
Exemple:
numere = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Numere pare
pare = list(filter(lambda x: x % 2 == 0, numere))
# [2, 4, 6, 8, 10]
# Numere > 5
mari = list(filter(lambda x: x > 5, numere))
# [6, 7, 8, 9, 10]
# Sterge valori None/goale
lista = [1, None, 2, "", 3, 0, 4]
curate = list(filter(None, lista))
# [1, 2, 3, 4] (pastreaza doar truthy)
Functia reduce()
Reduce un iterabil la o singura valoare (din functools):
from functools import reduce
reduce(functie, iterabil, [valoare_initiala])
Exemple:
from functools import reduce
numere = [1, 2, 3, 4, 5]
# Suma
total = reduce(lambda a, b: a + b, numere)
# 15
# Produs
produs = reduce(lambda a, b: a * b, numere)
# 120
# Cu valoare initiala
total = reduce(lambda a, b: a + b, numere, 10)
# 25 (10 + 1 + 2 + 3 + 4 + 5)
# Gasire maxim
maxim = reduce(lambda a, b: a if a > b else b, numere)
# 5
Comparatie cu List Comprehensions
numere = [1, 2, 3, 4, 5]
# map vs comprehension
list(map(lambda x: x**2, numere))
[x**2 for x in numere] # Mai clar
# filter vs comprehension
list(filter(lambda x: x > 2, numere))
[x for x in numere if x > 2] # Mai clar
Inlantuire
numere = range(1, 11)
# Patratele numerelor pare
rezultat = list(map(lambda x: x**2,
filter(lambda x: x % 2 == 0, numere)))
# [4, 16, 36, 64, 100]
# Echivalent comprehension (mai clar)
rezultat = [x**2 for x in numere if x % 2 == 0]
Puncte Cheie pentru Examen
map()transforma fiecare elementfilter()selecteaza elementelereduce()combina intr-o valoare (din functools)- Toate returneaza iteratori (converteste cu
list()) - Comprehensions sunt adesea mai clare