Python:在元组的元组上使用reduce
我想在Python中计算从点A到点B的路径长度,这个路径还要经过一系列中间点。我知道怎么做,但我想用内置的reduce函数。
到目前为止我尝试的,请注意,这完全是错误的,是这个:
reduce(lambda x,y: math.sqrt((y[1]-y[0])**2+(x[1]-x[0])**2) , ((1,2),(3,4),(1,8)))
有什么想法吗?
谢谢。
8 个回答
2
reduce()
这个函数其实不太适合用来做这个事情。虽然用reduce()
也能做到,但方式有点奇怪:
def distance((x, d), y):
return y, d + math.hypot(y[0] - x[0], y[1] - x[1])
print reduce(distance, [(3,4),(1,8)], ((1, 2), 0.0))[1]
输出结果是
7.30056307975
传给reduce()
的最后一个参数是起始点,也是距离的初始值。
4
虽然看起来不太好,但这是可以做到的 :-)
>>> tot = ((1,2),(3,4),(1,8))
>>> reduce(lambda d,((x0,y0),(x1,y1)): d + ((x1-x0)**2+(y1-y0)**2)**0.5, zip(tot[1:], tot[0:]), 0.0)
7.3005630797457695
6
你应该先进行映射,然后再进行归约。
points = [(1, 2), (3, 4), (1, 8)]
distances = (math.hypot(b[0]-a[0], b[1]-a[1])
for a, b in zip(points, points[1:]))
total_distance = sum(distances)
或者,如果你必须使用reduce()
,虽然sum()
在这个情况下更好:
import operator
total_distance = reduce(operator.add, distances)
如果你有很多点,使用NumPy可以帮助你快速一次性完成这些操作:
import numpy
total_distance = numpy.hypot(*numpy.diff(numpy.array(points), axis=0)).sum()
编辑:使用math.hypot()
并添加NumPy方法。