map() Methods will A function Map to each element of the sequence , Generate a new sequence , Contains all function return values .
Because the returned sequence is a Iterator,Iterator It's an inert sequence , So by list() The function lets it compute the entire sequence and return a list.
def fun(x):
return x*x
r = map(fun,[1,2,3,4,5,6,7,8,9])
print(list(r))
#map() As a higher-order function , In fact, it abstracts the rules of operation
print(list(map(str,[1,2,3,4,5,6,7,8,9]))) # Convert numbers to strings
print(list(map(lambda x:x**2, range(1,10)))) # Calculate the square of each element of the sequence
In the process of iterating the sequence , First turn on the First two elements ( Only two. ) Pass to function , After function processing , And then put The result and the third element Pass it as two parameters to the function parameter , The result of function processing is the same as the fourth element Pass it as two parameters to the function parameter , By analogy .
from functools import reduce
from tkinter import N
def fun_add(x,y):
return x+y
print(reduce(fun_add,[1,2,3,4,5,6,7,8,9]))
# perhaps
print(reduce(lambda x,y:x*10+y,range(1,10)))
Python The built-in filter() Function to filter the sequence . It's also a higher-order function , Delete the elements that match the filter function .
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# result : ['A', 'B', 'C']
use filter Find prime number
use Python To implement this algorithm , You can first construct a from 3 The beginning of the odd sequence :
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
Then define a filter function :
def _not_divisible(n):
return lambda x: x % n > 0
Last , Define a generator , Keep going back to the next prime :
def primes():
yield 2
it = _odd_iter() # Initial sequence
while True:
n = next(it) # Returns the first number of the sequence
yield n
it = filter(_not_divisible(n), it) # Construct a new sequence
# Print 1000 Prime number within :
for n in primes():
if n < 1000:
print(n)
else:
break
sorted() Function is also a higher-order function , It can also receive a key Function to implement custom sorting , For example, order by absolute value :
print(sorted([36, 5, -12, 9, -21], key=abs))
#[5, 9, -12, -21, 36]
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
#['Credit', 'Zoo', 'about', 'bob']
String sort
# Ignore case sorting
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
#['about', 'bob', 'Credit', 'Zoo']
# Reverse sorting , No need to change key function , You can pass in the third parameter reverse=True:
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
#['Zoo', 'Credit', 'bob', 'about']