1. 程式人生 > >python學習-基礎-函數語言程式設計

python學習-基礎-函數語言程式設計

  1. 高階函式
# 高階函式
# 函式本身也可以賦值給變數,即:變數可以指向函式。
# 既然變數可以指向函式,函式的引數能接收變數,那麼一個函式就可以接收另一個函式作為引數,這種函式就稱之為高階函式。
def add3(x, y, f):
    return f(x) + f(y)

# map/reduce
# Python內建了map()和reduce()函式。
# map()傳入的第一個引數是f,即函式物件本身。由於結果r是一個Iterator,Iterator是惰性序列,因此通過list()函式讓它把整個序列都計算出來並返回一個list。
# 
def fun1(x):
	return x * x
reslut1 = map(fun1, [1,12,23,4])

# reduce把一個函式作用在一個序列[x1, x2, x3, ...]上,這個函式必須接收兩個引數,reduce把結果繼續和序列的下一個元素做累積計算,
def fun2(x, y):
	return x * 10 + y

print(reduce(fun2, [1, 3, 5, 7, 9])) # 135789

def char2num(s):
	digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
	return digits[s]
print(reduce(fun2, map(char2num, '123546')))

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))

# 把使用者輸入的不規範的英文名字,變為首字母大寫,其他小寫的規範名字

def fun4 (s):
	if isinstance(s, str):
		return s[:1].upper() + s[1:].lower()
		# return name.capitalize()
list7 = ['adam', 'LISA', 'barT']
res2 = list(map(fun4, list7))
print(res2)

#請編寫一個prod()函式,可以接受一個list並利用reduce()求積:
def fun5():
	def fun6 (x, y):
		return x * y
	return reduce(fun6, [3,5,7,9])
print(fun5())

# 利用map和reduce編寫一個str2float函式,把字串'123.456'轉換成浮點數123.456:
def str2float(str):
	def fun7(s):
		return int(s)
	def fun8(x, y):
		return x + y / 1000
	l1 = (str.split('.')[0],str.split('.')[1])
	l2 = list(map(fun7, l1))
	print(reduce(fun8, l2))

str2float('123.456')

# filter 過濾序列
# 
def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))

def is_palindrome(n):
    n1 = str(n) 
    # n1[::-1] 翻轉字串
    if n1[::] == n1[::-1]:
        return n1

output = list(filter(is_palindrome,range(1,1000)))
print(output)

# sorted 排序演算法
# sorted()函式也是一個高階函式,它還可以接收一個key函式來實現自定義的排序,例如按絕對值大小排序:
sorted([36, 5, -12, 9, -21], key=abs)
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
# 要進行反向排序,不必改動key函式,可以傳入第三個引數reverse=True
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
# 請用sorted()對上述列表分別按名字排序:
# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\
list10 = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name (t):
	return t[0]
def by_scr (t):
	return t[1]
# list11 = sorted(list10, key=by_name)
list11 = sorted(list10, key=by_scr, reverse=True)
print(list11)

  1. 函式作為返回值
# 函式作為返回值
# 高階函式除了可以接受函式作為引數外,還可以把函式作為結果值返回。
# 可變引數求和
def lazy_sum(*args):
    # ax = 0
    # for n in args:
    #     ax = ax + n
    # return ax
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax
    return sum

# 閉包
# 匿名函式 lambda
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
# 通過對比可以看出,匿名函式lambda x: x * x實際上就是:
# def f(x):
#    return x * x
#關鍵字lambda表示匿名函式,冒號前面的x表示函式引數。名函式有個限制,就是隻能有一個表示式,不用寫return,返回值就是該表示式的結果。
# 因為函式沒有名字,不必擔心函式名衝突。此外,匿名函式也是一個函式物件,也可以把匿名函式賦值給一個變數,再利用變數來呼叫該函式:
# f = lambda x: x * x
# 可以把匿名函式作為返回值返回,比如: 
# def build(x, y):
#    return lambda: x * x + y * y
print(list(filter(lambda x: x % 2 == 1, range(1 ,20))))

  1. 裝飾器 decorator
# 裝飾器 decorator
# 函式物件有一個__name__屬性,可以拿到函式的名字: now.__name__
# 
# 比如,在函式呼叫前後自動列印日誌,但又不希望修改now()函式的定義,這種在程式碼執行期間動態增加功能的方式,稱之為“裝飾器”(Decorator)。
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper
# 觀察上面的log,因為它是一個decorator,所以接受一個函式作為引數,並返回一個函式。我們要藉助Python的@語法,把decorator置於函式的定義處:

@log
def now():
    print('2015-3-25')

# 把@log放到now()函式的定義處,相當於執行了語句:
# now = log(now)
now()

# 如果decorator本身需要傳入引數,那就需要編寫一個返回decorator的高階函式,寫出來會更復雜。比如,要自定義log的文字:
def log1(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator
# 這個3層巢狀的decorator用法如下:
@log1('execute')
def now1():
    print('2015-3-25')

# 相比,巢狀效果 now = log('execute')(now)
now1()

#因為返回的那個wrapper()函式名字就是'wrapper',所以,需要把原始函式的__name__等屬性複製到wrapper()函式中,否則,有些依賴函式簽名的程式碼執行就會出錯。

#不需要編寫wrapper.__name__ = func.__name__這樣的程式碼,Python內建的functools.wraps就是幹這個事的,所以,一個完整的decorator的寫法如下:
import functools
import time
def log2(func):
    @functools.wraps(func)
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper
# 或者針對帶引數的decorator:
def log3(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print('%s %s():' % (text, func.__name__))
            return func(*args, **kw)
        return wrapper
    return decorator
# 請設計一個decorator,它可作用於任何函式上,並列印該函式的執行時間:
# 
def metric(fn):
	@functools.wraps(fn)
	def wrapper (*args, **kw):
		t1 = time.time()
		f = fn(*args, **kw)
		t2 = time.time()
		print('%s executed in %s ms' % (fn.__name__, (t2 - t1) * 1000))
		return f
	return wrapper


#寫出一個@log的decorator,使它既支援: @log @log('execute')
def log3(arg):
	# 判斷引數是否存在
	
    if not isinstance(arg,str):
        def wrapper(*args,**kw):
            print('begin call %s' % arg.__name__)
            temp = arg(*args,**kw)
            print('end call %s' % arg.__name__)
            return temp
        return wrapper
    else:
        def execute(fn):
            @functools.wraps(fn)
            def wrapper2(*args,**kw):
                    print('%s begin call %s' % (arg,fn.__name__))
                    temp = fn(*args,**kw)
                    print('%s end call %s' % (arg,fn.__name__))
                    return temp
            return wrapper2
        return execute
  1. 偏函式
# 偏函式
# functools.partial就是幫助我們建立一個偏函式的,不需要我們自己定義int2(),
def int2(x, base=2):
    return int(x, base)
# 可以直接使用下面的程式碼建立一個新的函式int2:
int2 = functools.partial(int, base=2)

print(int2('1000000'))

# 簡單總結functools.partial的作用就是,把一個函式的某些引數給固定住(也就是設定預設值),返回一個新的函式,呼叫這個新函式會更簡單。
max2 = functools.partial(max, 10)

# 相當於:
# args = (10, 5, 6, 7)
# max(*args)