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

Python advanced (6): functional programming

編輯:Python

Functional programming

Definition

     Functional programming is a programming paradigm , Treat computer operations as calculations of functions

characteristic

  • Think of calculations as functions
  • The code is simple and easy to read and understand
  • Variables are allowed
  • Support higher-order functions ( Function as variable )、 Closure ( Return function ) And anonymous functions

Use

# Take the function as an argument 
import math
def add(x, y, f):
return f(x) + f(y)
print(add(-1, 9, abs)) # ==> 10
print(add(4, 16, math.sqrt)) # ==> 6.0
'''map() function Receive a function f And a list, And put the function f It works on list On each element of , Also returns an iterator , You can iterate in turn to get the original list The result of element processing '''
def formatter(x):
return x[0].upper() + x[1:].lower()
for item in map(formatter, ['john', 'TIMY', 'DaniEl']):
print(item) # ⇒ John Timy Daniel
'''reduce() function Receive a function f And a list, Yes list Each element of calls the function repeatedly f, And return the final result , You can accept the third parameter as the initial value Python2 Can be used directly in ,Python3 Need to be in functools Introduced in package '''
from functools import reduce
def f(x, y):
return x * y
print(reduce(f, [1, 3, 5, 7, 9])) # ⇒ 945
'''filter() function Receive a function f And a list, By function f Judge each element , return True or False,filter() Automatically filter out the unqualified elements according to the judgment results and return an iterator , All qualified elements can be iterated out '''
import math
def is_integer(x):
r = int(math.sqrt(x))
return math.pow(r, 2) == x
for item in filter(is_integer, range(1,101)):
print(item) # ⇒ 1 4 9 16 25 36 49 64 81 100
'''sorted() function Sort from small to large by default , When list When each element is a container , Will be sorted by the first element , Back to a new list If you need to specify a field to sort ,key The parameter value is a function , Receive the elements of the list to be sorted as parameters and return the corresponding fields to be sorted If reverse order is needed , You need to specify reverse Parameter is True '''
def k(item):
return item.lower()
name = ['boom', 'about', 'Dog', 'Large']
print(name) # ⇒ ['boom', 'about', 'Dog', 'Large']
newName = sorted(name, key=k)
print(newName) # ⇒ ['about', 'boom', 'Dog', 'Large']
''' Return function You can define subfunctions inside a function , At the same time, you can return the sub function to Cannot return a function with parentheses , When returning a function value, you need '''
from functools import reduce
def f(x, y):
return x * y
def calc_prod(list_):
def prod():
return reduce(f, list_, 1)
return prod
p = calc_prod([1,2,3,4,5])
print(p()) # ⇒ 120
''' Closure The inner function references the variables of the outer function , And return the result of the inner function Be careful : Return function should not refer to any cyclic variable or variable that will change later '''
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j * j
return g
k = f(i)
fs.append(k)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3()) # ⇒ (1, 4, 9)
''' Anonymous functions Anonymous function usage lambda The keyword is defined ,lambda x,y: x + y, You can complete the definition of the function , A colon precedes an anonymous function parameter , The colon is followed by an expression , Do not write return, The return value is the result of the expression '''
name = ['boom', 'about', 'Large', 'Dog']
print(sorted(name, key=lambda x:x.lower())) # ⇒ ['about', 'boom', 'Dog', 'Large']
'''' No parameters decorator It is essentially a higher order function , Receive a function as an argument , Returns a new function Use @ grammar , You can avoid writing code manually '''
# Contains only one parameter 
def log(f):
def fn(x):
print('call ' + f.__name__ + '()...')
return f(x)
return fn
# Contains any number of parameters 
def log(f):
def fn(*args, **kwargs):
print('call ' + f.__name__ + '()...')
return f(*args, **kwargs)
return fn
# Output function run time 
import time
def performance(f):
def fn(*args, **kwargs):
t1 = time.time()
r = f(*args, **kwargs)
t2 = time.time()
print('call %s() in %fs' % (f.__name__, (t2-t1)))
return r
return fn
@performance
def add(x, y):
return x + y
add(1, 2) # ⇒ call add() in 0.000003s 3
@performance
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
factorial(10) # ⇒ call factorial() in 0.004084s
''' Parametric decorator Parameterized decorator First return to a decorator function , Let this decorator Function receives a function and returns a new function , It is equivalent to that in the original two-level function , Added a layer of nesting '''
import time
def performance(param):
def performance_decorator(f):
def fn(*args, **kwargs):
t1 = time.time()
r = f(*args, **kwargs)
t2 = time.time()
if param == 's':
print('call %s() in %fs' % (f.__name__, (t2-t1)))
if param == 'ms':
print('call %s() in %fms' % (f.__name__, (t2-t1)*1000))
return r
return fn
return performance_decorator
@performance('ms')
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
factorial(10) # ⇒ call factorial() in 3.329039ms call factorial() in 0.003894s
''' Partial function Create a function that calls another preset parameter or variable partial You can change a function with many parameters into a new function with few parameters , The missing parameter needs to specify the default value '''
from functools import partial
sorted_ignore_case = partial(sorted, key=lambda x: x.lower())
print(sorted_ignore_case(['boom', 'about', 'Large', 'Dog'])) # ⇒ ['about', 'boom', 'Dog', 'Large']

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