我有一个未还原点(2D)的列表,我想计算它们之间的距离之和。 因为我的背景是c ++开发人员,所以我会这样做:
import math
class Point:
def __init__(self, x,y):
self.x = x
self.y = y
def distance(P1, P2):
return math.sqrt((P2.x-P1.x)**2 + (P2.y-P1.y)**2)
points = [Point(rand(1), rand(1)) for i in range(10)]
#this part should be in a nicer way
pathLen = 0
for i in range(1,10):
pathLen += distance(points[i-1], points[i])
是否有更多的Python方式替换for循环?例如用reduce或类似的方法?
最诚挚的问候!
答案 0 :(得分:2)
您可以将生成器表达式与sum
,zip
和itertools islice
结合使用,以避免重复数据:
from itertools import islice
paathLen = sum(distance(x, y) for x, y in zip(points, islice(points, 1, None)))
这里有live example
答案 1 :(得分:1)
一些修复,因为C ++方法可能不是最好的解决方法
import math
# you need this import here, python has no rand in the main namespace
from random import random
class Point:
def __init__(self, x,y):
self.x = x
self.y = y
# there's usually no need to encapsulate variables in Python
def distance(P1, P2):
# your distance formula was wrong
# you were adding positions on each axis instead of subtracting them
return math.sqrt((P1.x-P2.x)**2 + (P1.y-P2.y)**2)
points = [Point(random(), random()) for i in range(10)]
# use a sum over a list comprehension:
pathLen = sum([distance(points[i-1], points[i]) for i in range(10)])
@Robin Zigmond的zip
方法也是一种很好的实现方法,尽管对我来说并不是立即可以在这里使用它。