运行结果
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