Python:减少元组的元组

lc2*_*817 4 python reduce lambda euclidean-distance

我试图在Python中计算从A点到B点通过中间点列表的路径长度.我知道怎么做,但我确实想使用reduce Built-in功能.

为什么我到目前为止尝试过,请注意这是完全错误的,是这样的:

reduce(lambda x,y: math.sqrt((y[1]-y[0])**2+(x[1]-x[0])**2) , ((1,2),(3,4),(1,8)))
Run Code Online (Sandbox Code Playgroud)

任何的想法?

谢谢.

Mic*_*man 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)
Run Code Online (Sandbox Code Playgroud)

或者,如果你必须使用reduce(),虽然sum()为此目的更好:

import operator

total_distance = reduce(operator.add, distances)
Run Code Online (Sandbox Code Playgroud)

如果你有很多积分,你可能会发现NumPy有助于一次完成这一切,很快:

import numpy

total_distance = numpy.hypot(*numpy.diff(numpy.array(points), axis=0)).sum()
Run Code Online (Sandbox Code Playgroud)

编辑:使用math.hypot()并添加NumPy方法.

  • 数学中有函数hypot (2认同)