functools模块

xiaoxiao2025-11-11  40

functools中的partial 偏函数 自动传参,比如一个函数要传三个参数,只传一个就行了,因为内部已经处理了 帮助开发者自动传递参数 import functools def index(a1, a2): return a1 + a2 new_func = functools.partial(index, 666) # 生成了一个新的函数 ret = new_func(1) # 新的函数加括号就执行了index,由于已经传了一个参数666, 只要传第二个参数就行了 print(ret)

运行结果

667

import random import math from functools import partial # functools函数加强版模块,相当内置函数的补充 fnx = lambda: random.randint(0, 10) # 随机十组坐标 data = [(fnx(), fnx()) for c in range(10)] print(data) target = (2, 4) # 计算欧氏距离函数 def euclid_dist(v1, v2): x1, y1 = v1 x2, y2 = v2 # print(v1, v2) return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # data.sort(key=euclid_dist) # partial的作用是当有些函数只能传函数名不能传参数时(sort,filter,map等),可以用partial方法传参数 p_euclid_dist = partial(euclid_dist, target) # v1固定是target # a = p_euclid_dist((4)) # print(a) data.sort(key=p_euclid_dist) # 把data中的十个坐标依次与传给p_euclid_dist中的v2,再排序data print(data) for p in data: print(round(p_euclid_dist(p), 3)) # 计算的结果打印

运行结果

[(3, 7), (3, 6), (10, 6), (7, 10), (9, 1), (9, 8), (8, 7), (7, 3), (2, 3), (2, 8)] [(2, 3), (3, 6), (3, 7), (2, 8), (7, 3), (8, 7), (9, 1), (7, 10), (9, 8), (10, 6)] 1.0 2.236 3.162 4.0 5.099 6.708 7.616 7.81 8.062 8.246 functools中的reduce函数 from functools import reduce print(reduce(lambda x,y: x+y, [1, 2, 3])) # 运行过程(initial=None,sequence=[1, 2, 3], funtion= lambda x, y: x + y): (1 + 2) + 3 print(reduce(lambda x, y: x/y, [1,2,3], 9)) # 运行过程 : ((9 / 1) / 2 ) / 3 print(reduce(lambda x,y: x-y, [1, 2, 3], 7)) # 运行过程 : ((7 - 1) - 2) - 3

运行结果

6 1.5 1
转载请注明原文地址: https://www.6miu.com/read-5039461.html

最新回复(0)