所以我有一个积分列表
["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
起点为
["2.2 4.6"]
现在我要做的是获得最接近我的起点,然后是最接近该点的点,依此类推。
所以我得计算距离
def dist(p1,p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
但同样,我试图最接近我的起点,然后是最接近那个的点,依此类推。
好吧,因为你抱怨我没有显示足够的代码?fList = ["2.5 3.6", "9.5 7.5", "10.2 19.1", "9.7 10.2", "5.5 6.5", "7.8 9.8"]
def distance(points):
p0, p1 = points
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
min_pair = min(itertools.combinations(fList, 2), key=distance)
min_distance = distance(min_pair)
print min_pair
print min_distance
所以我得到了我的起点
([2.2, 4.6], [2.5, 3.6])
所以现在我需要使用2.5,3.6作为我的起点并找到下一个最接近的等等
有没有人做过类似的事情?
答案 0 :(得分:2)
可能的方法是使用广度优先搜索来扫描所有元素,并找到从队列中弹出的每个元素的最近点:
import re, collections
import math
s = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
def cast_data(f):
def wrapper(*args, **kwargs):
data, [start] = args
return list(map(lambda x:' '.join(map(str, x)), f(list(map(lambda x:list(map(float, re.findall('[\d\.]+', x))), data)), list(map(float, re.findall('[\d\.]+', start))))))
return wrapper
@cast_data
def bfs(data, start, results=[]):
queue = collections.deque([start])
while queue and data:
result = queue.popleft()
possible = min(data, key=lambda x:math.hypot(*[c-d for c, d in zip(result, x)]))
if possible not in results:
results.append(possible)
queue.append(possible)
data = list(filter(lambda x:x != possible, data))
return results
print(bfs(s, ["2.2 4.6"]))
输出:
['2.5 3.6', '5.5 6.5', '7.8 9.8', '9.7 10.2', '9.5 7.5', '10.2 19.1']
结果是最近点的列表,使用math.hypot
确定。
答案 1 :(得分:1)
您可以尝试以下代码。更简单,更简短。使用比较器根据距起点(2.2,4.6)
import math
data = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
data.sort(key=lambda x: math.sqrt((float(x.split(" ")[0]) - 2.2)**2 +
(float(x.split(" ")[1]) -4.6)**2))
print(data)
# output ['2.5 3.6', '5.5 6.5', '7.8 9.8', '9.5 7.5', '9.7 10.2', '10.2 19.1']
答案 2 :(得分:0)
您可以根据需要简单地定义sort a list by a key - f.e.通过你的距离函数:
import math
def splitFloat(x):
"""Split each element of x on space and convert into float-sublists"""
return list(map(float,x.split()))
def dist(p1, p2):
# you could remove the sqrt for computation benefits, its a symetric func
# that does not change the relative ordering of distances
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
p = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
s = splitFloat("2.2 4.6") # your start point
p = [splitFloat(x) for x in p] # your list of points
# sort by distance between each individual x and s
p.sort(key = lambda x:dist(x,s))
d = [ (dist(x,s),x) for x in p] # create tuples with distance for funsies
print(p)
print(d)
输出:
[[2.5, 3.6], [5.5, 6.5], [7.8, 9.8], [9.5, 7.5], [9.7, 10.2], [10.2, 19.1]]
[(1.0440306508910546, [2.5, 3.6]), (3.8078865529319543, [5.5, 6.5]),
(7.64198926981712, [7.8, 9.8]), (7.854934754662192, [9.5, 7.5]),
(9.360021367496977, [9.7, 10.2]), (16.560495161679196, [10.2, 19.1])]