程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of Python high-order functions, high-order built-in functions and coriolism

編輯:Python

Python Higher order function 、 Higher order built-in functions and coriolism

  • 1、 Higher order function
    • 1.1 Python function
    • 1.2 Higher order function
    • 1.3 Implement the higher-order function of the counter
    • 1.4 Notice the difference between the following two functions
      • 1.4.1 Function nested function
      • 1.4.2 The function returns the global function
  • 2、 Built in higher-order function
    • 2.1 Sort sorted
      • 2.1.1 grammar
      • 2.1.2 Example
    • 2.2 Filter filter
      • 2.2.1 grammar
      • 2.2.2 Example
    • 2.3 mapping map
      • 2.3.1 grammar
      • 2.3.2 Example
  • 3、 currying
    • 3.1 Concept
    • 3.2 Example

1、 Higher order function

1.1 Python function

  • Function in Python Li is a first-class citizen (First-Class Object)
  • Functions are also objects , Is a callable object
  • Functions can be used as ordinary variables , It can also be used as an argument to a function 、 Return value

1.2 Higher order function

In mathematics and Computer Science , Higher order function (High-order Function) Functions that should satisfy at least one of the following conditions :

  • Take one or more functions as arguments
  • Output a function

1.3 Implement the higher-order function of the counter

def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
# The base number is 0, In steps of 2 Technical device for 
counter1 = counter(base=0)
for i in range(3):
print(counter1(step=2))
# Out
2
4
6

1.4 Notice the difference between the following two functions

1.4.1 Function nested function

# == If you can't compare content , It is equivalent to is
# for example Function object Unable to compare content Just compare the memory addresses directly 
def counter(base):
def _counter(step=1):
nonlocal base
base += step
return base
return _counter
f1 = counter(5)
f2 = counter(5)
print('f1 = {}, f2 = {}'.format(f1, f2))
print('f1_id = {}, f2_id = {}'.format(id(f1), id(f2)))
print('f1() = {}, f2() = {}'.format(f1(), f2()))
print('f1()_id = {}, f2()_id = {}'.format(id(f1()), id(f2())))
print(f1 == f2)
print(f1() == f2())
f1 = <function counter.<locals>._counter at 0x00000000078B13A8>, f2 = <function counter.<locals>._counter at 0x00000000078B1558>
f1_id = 126555048, f2_id = 126555480
f1() = 6, f2() = 6
f1()_id = 8791210553808, f2()_id = 8791210553808
False
True

1.4.2 The function returns the global function

# == If you can't compare content , It is equivalent to is
# for example Function object Unable to compare content Just compare the memory addresses directly 
# Globally defined functions , It is equivalent to a global variable , No matter how many variables are assigned , Its id It's all the same 
inc_num = 100
def inc(step=1):
return inc_num+1
def counter(base=0):
print(id(inc))
return inc
print(1, inc, id(inc), id(inc()))
counter()
print(2, inc, id(inc), id(inc()))
f1 = counter(5)
f2 = counter(7)
print('f1 = {}, f2 = {}'.format(f1, f2))
print('f1_id = {}, f2_id = {}'.format(id(f1), id(f2)))
print('f1() = {}, f2() = {}'.format(f1(), f2()))
print('f1()_id = {}, f2()_id = {}'.format(id(f1()), id(f2())))
print(f1 == f2)
print(f1() == f2())
1 <function inc at 0x0000000008032C18> 134425624 8791210556816
134425624
2 <function inc at 0x0000000008032C18> 134425624 8791210556816
134425624
134425624
f1 = <function inc at 0x0000000008032C18>, f2 = <function inc at 0x0000000008032C18>
f1_id = 134425624, f2_id = 134425624
f1() = 101, f2() = 101
f1()_id = 8791210556816, f2()_id = 8791210556816
True
True

2、 Built in higher-order function

2.1 Sort sorted

2.1.1 grammar

  • sorted(iterable, /, *, key=None, reverse=False)
  • sorted The function returns a new list
  • Pay attention to and list.sort()( Modify in place , The return is None) The difference between

2.1.2 Example

  • sorted function And list sort Method The difference between

    list1 = [1, 2, 3]
    list2 = sorted(list1, key=lambda x:6-x) # Does not affect the original list , Return to the new list 
    print(list1, list2)
    # [1, 2, 3] [3, 2, 1]
    
    list1 = [1, 2, 3]
    list2 = list1.sort(key=lambda x:6-x) # Modify in place 
    print(list1, list2)
    # [3, 2, 1] None
    
  • sorted function

    list3 = [1, 2, 3, 'a', 'b', 'A']
    list4 = sorted(list3, key=str)
    list5 = sorted(list3, key=str, reverse=True)
    for i in [list3, list4, list5]:
    print(i)
    for j in list3:
    print(ord(str(j)), end=' |=| ')
    
    [1, 2, 3, 'a', 'b', 'A']
    [1, 2, 3, 'A', 'a', 'b']
    ['b', 'a', 'A', 3, 2, 1]
    49 |=| 50 |=| 51 |=| 97 |=| 98 |=| 65 |=|
    
    # ord() Built in function help 
    Signature: ord(c, /)
    Docstring: Return the Unicode code point for a one-character string.
    Type: builtin_function_or_method
    

2.2 Filter filter

2.2.1 grammar

  • filter(self, /, *args, **kwargs)
  • filter(function or None, iterable) --> filter object
  • Iterate over the iteratable object , Returns an iterator
  • function A parameter is a function of a parameter , And the return value should be bool type , Or its return value is equivalent to Boolean value
  • function If the parameter is None, Each element of an iteratable object has its own Boolean equivalent

2.2.2 Example

# Filter out the list that cannot be 3 It can't be divided 2 The value of the division 
iter1 = filter(lambda x:x%3!=0 and x%2!=0, list(range(10)))
# Returns an iterator 
print(iter1, type(iter1))
print(list(iter1))
<filter object at 0x0000000007B02E88> <class 'filter'>
[1, 5, 7]
# function If the parameter is `None`, Each element of an iteratable object has its own Boolean equivalent 
print(list(filter(None, range(5))))
print(list(filter(None, range(-5, 5))))
print(list(filter(None, [0, False, True, [], [1], {
}, {
1}])))
[1, 2, 3, 4]
[-5, -4, -3, -2, -1, 1, 2, 3, 4]
[True, [1], {
1}]
# if fn(element): yield element
print(list(filter(lambda x:True, range(5))))
print(list(filter(lambda x:False, range(5))))
print(list(filter(lambda x:None, range(5))))
[0, 1, 2, 3, 4]
[]
[]

2.3 mapping map

2.3.1 grammar

  • map(self, /, *args, **kwargs)
  • map(func, *iterables) --> map object
  • For elements of multiple iteratible objects , Map according to the specified function
  • Returns an iterator

2.3.2 Example

iter2 = map(lambda x:x+1, range(5))
print(iter2, type(iter2))
print(list(iter2))
<map object at 0x0000000007B295C8> <class 'map'>
[1, 2, 3, 4, 5]
print(list((map(lambda x:x**2, range(1,6)))))
print(dict((map(lambda x:(x, x**2), range(1,6)))))
print(dict((map(lambda x, y:(x, y**2), 'abcde', range(1,4)))))
[1, 4, 9, 16, 25]
{
1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{
'a': 1, 'b': 4, 'c': 9}
# set Sets are unordered 
dict(map(lambda x,y:{
x, y}, 'abcde', range(10)))
# {0: 'a', 1: 'b', 2: 'c', 3: 'd', 'e': 4}

3、 currying

3.1 Concept

  • The process of changing a function that accepts multiple parameters into a new process that accepts one parameter
  • The new function returns a function with the original second parameter as the parameter
  • Such as z=f(x, y) To z=f(x)(y)

3.2 Example

def add(x, y):
return x + y
add(4, 5)
# 9
def add(x):
def _add(y):
return x + y
return _add
add(4)(5)
# 9
def add(x, y, z):
return x + y + z
add(4, 5, 6)
# 15
def add(x):
def _add(y):
def _add1(z):
return x + y + z
return _add1
return _add
add(4)(5)(6)
# 15

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved