将结果从一个"for"循环迭代传递到下一个迭代?



我有一个纬度/经度坐标列表,我想从中创建一条线:

import time
import random
class Point:
def __init__(self, lng, lat, neighbours):
self.x = lng
self.y = lat
self.neighbours = neighbours
def find_neighbours(point):
'''Simulate neighbour search in kdtree'''
print(f'Searching for {point} in the tree')
time.sleep(1)
neighbours = random.randint(0, 100)
return neighbours
class Line:
def __init__(self, point_A, point_B):
self.point_A = point_A
self.point_B = point_B
self.line = [
point_A, 
point_B,
]
def get_points():
return [
[51.11453, 17.10942],
[51.11441, 17.10941],
[51.11349, 17.10779],
[51.11367, 17.10733],
[51.1143, 17.10648],
[51.11493, 17.10553],
[51.11471, 17.10519],
[51.11434, 17.10506],
[51.11376, 17.10462],
[51.11372, 17.10433],
[51.11353, 17.1042],
[51.11388, 17.10168],
[51.11386, 17.10108],
[51.11362, 17.10098],
[51.11177, 17.10099],
[51.11169, 17.10105],
[51.11169, 17.10129],
]
def make_lines_from_points(points):
lines = []
for index, point in enumerate(points):
try:
next_point = points[index + 1]
except IndexError: 
# last point reached, so no need to make a line
next_point = None
if next_point:
point_A = Point(
point[1],
point[0],
find_neighbours(point)
)
point_B = Point(
next_point[1],
next_point[0],
find_neighbours(next_point)
)
line = Line(point_A, point_B)
lines.append(line.line)
return lines
def main():
points = get_points()
lines = make_lines_from_points(points)
print(lines)
if __name__ == '__main__':
main()

在此代码中,我将每个坐标及其旁边的坐标转换为类Point实例,然后从这两个点创建和Line实例。

初始化每个Point实例时,必须找到点的邻居并将其分配给实例的neighbours属性。这可能需要更长的时间。

考虑到这一点,我想改进for循环,使 B 点在下一次迭代中成为 A 点,以避免再次计算同一点的邻居。

我该怎么做?

你可以试试这个:

def make_lines_from_points(points):
lines = []
saved_neighbours = None
for index, point in enumerate(points):
try:
next_point = points[index + 1]
except IndexError: 
# last point reached, so no need to make a line
next_point = None
if next_point:
point_A = Point(
point[1],
point[0],
saved_neighbours if saved_neighbours is not None else find_neighbours(point)
)
point_B = Point(
next_point[1],
next_point[0],
find_neighbours(next_point)
)
line = Line(point_A, point_B)
lines.append(line.line)
saved_neighbours = point_B.neighbours
return lines
def make_lines_from_points(points):
lines = []
point_A = None
for index, point in enumerate(points):
try:
next_point = points[index + 1]
except IndexError: 
# last point reached, so no need to make a line
next_point = None
if next_point:
if not point_A:
point_A = Point(
point[1],
point[0],
find_neighbours(point)
)
point_B = Point(
next_point[1],
next_point[0],
find_neighbours(next_point)
)
point_A = point_B
line = Line(point_A, point_B)
lines.append(line.line)
return lines

最新更新