Python anonymous function (lambda)

Time:2020-11-12

Compared with normal writing, using anonymous functions is quite concise

  • Map () traverses all
a = [1, 2, 3]
x = []
for each in a:
    x.append(each+1)

print(x)
###Using map (func, Iterable)
print(list(map(lambda x: x+1, a)))
  • Reduce (func, SEQ) accumulates the value of each calculation
def num(x, y):
    return x + y
print(reduce(num, [1, 2, 3, 4]))
--------------------------
print(reduce(lambda x, y: x*y, [1, 2, 3, 4]))
  • Filter (func, Iterable) filters the values that meet the conditions
 
print(list(filter(lambda x: x%2==0,range(10))))

 

This article first appeared on Python black hole, and the blog Garden was updated synchronously