Catalog
Map,Filter and Reduce
Map
Filter
Reduce
set( aggregate ) data structure
intersection
Difference set
Map,Filter and Reduce Three functions can facilitate functional programming . We will discuss and understand them one by one through examples .
Map A function is mapped to all elements of an output list . This is its specification :
map(function_to_apply, list_of_inputs)
Most of the time , We need to pass all the elements in the list to a function one by one , And collect the output . For example :
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map It can be achieved in a much simpler and more beautiful way . this is it :
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Most of the time , We use anonymous functions (lambdas) To match map, So I did the same thing above . Not only for the input of a list . We can even use a list of functions !
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x: x(i), funcs)
print(list(value))
# translator's note : above print when , added list transformation , In order to python2/3 The compatibility of
# stay python2 in map Go directly back to the list , But in python3 Return iterator
# So in order to be compatible with python3, need list Change my
seeing the name of a thing one thinks of its function ,filter Filter the elements in the list , And return a list of all the elements that meet the requirements , If the function is mapped to the element, the return value is True. Here is a short example :
number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))
# translator's note : above print when , added list transformation , In order to python2/3 The compatibility of
# stay python2 in filter Go directly back to the list , But in python3 Return iterator
# So in order to be compatible with python3, need list Change my
# Output: [-5, -4, -3, -2, -1]
This filter Similar to a for loop , But it is a built-in function , And faster .
Be careful : If map and filter If it doesn't look elegant to you , So you can look at another chapter : list / Dictionaries / Tuple derivation .
translator's note : In most cases, the derivation is more readable
When you need to do some calculations on a list and return results ,Reduce It's a very useful function . for instance , When you need to calculate the product of a list of integers .
Usually in python You may use basic for Loop to complete the task .
Now let's try reduce:
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
set( aggregate ) Is a very useful data structure . It is associated with the list (list) The behavior of is similar to , The difference lies in set Cannot contain duplicate values .
This is very useful in many cases . For example, you might want to check whether the list contains duplicate elements , You have two choices , The first one needs to use for loop , Just like this. :
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = []
for value in some_list:
if some_list.count(value) > 1:
if value not in duplicates:
duplicates.append(value)
print(duplicates)
### Output : ['b', 'n']
But there is a simpler and more elegant solution , That's using sets (sets), You just do it :
some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n']
duplicates = set([x for x in some_list if some_list.count(x) > 1])
print(duplicates)
### Output : set(['b', 'n'])
Collections have some other methods , Let's introduce some of them .
You can be right ⽐ The intersection of two sets ( Data in both sets ), as follows :
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.intersection(valid))
### Output : set(['red'])
You can use difference sets (difference) Find valid data , It is equivalent to subtracting the data of another set from one set , example
Such as :
valid = set(['yellow', 'red', 'blue', 'green', 'black'])
input_set = set(['red', 'brown'])
print(input_set.difference(valid))
### Output : set(['brown'])
You can also use symbols to create collections , Such as :
a_set = {'red', 'blue', 'green'}
print(type(a_set))
### Output : <type 'set'>
Collections have some other methods , I would suggest that you visit the official documents and do a quick reading .