map Will ⼀ Functions are mapped to ⼀ individual transport ⼊ list On all elements of .
amount to Batch input collect Batch output .
⼤ Most of the time , send ⽤ Anonymous functions (lambda) To match map.
# The most basic method
inputs = [1, 2, 3, 4, 5, 6]
outputs = []
for i in inputs:
outputs.append(i ** 3)
print(outputs)
Simplify
# Now the way
inputs = [1, 2, 3, 4, 5, 6]
outputs = list(map(lambda x: x ** 3, inputs))
print(outputs)
You can even enter a series of functions in batches .
# Batch input a series of functions
def Func1(x):
return x * x
def Func2(x):
return x + x
FuncList = [Func1, Func2]
for i in range(5):
res = map(lambda x: x(i), FuncList)
print(list(res))
The output is A set of lists :
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
stay python2 in map Go straight back to list ;
stay python3 Back in iterator ;
For compatibility python3, need list transformation ⼀ Next ;
filter Filter the elements in the list
filter return ⼀ A list of all elements that meet the requirements
Meet the requirements : When the function maps to this element, the return value is True
filter Be similar to ⼀ individual for loop , But it is ⼀ individual Built in functions , And faster .
# filter Example
inputs = range(-10, 10)
outputs = list(filter(lambda x: x < 0, inputs))
print("The numbers which are less than 0 are: {}".format(outputs))
The output is :
The numbers which are less than 0 are: [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
stay python2 in filter Go straight back to list ;
stay python3 Back in iterator ;
For compatibility python3, need list transformation ⼀ Next ;
When need is right ⼀ A list Conduct ⼀ Some calculations and Return results when ,Reduce Will become very useful .
for example : Calculate the sum of the squares of a list of integers .
# reduce Example
from functools import reduce
inputs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
outputs = reduce(lambda x, y: x + y, inputs)
The output is :
print(" And is :{}".format(outputs))