我有一个二维元组列表,未分类和n大小.我想找到哪个元组与X和Y的维度最接近.最好的方法是什么?
target = (75, 75)
values = [
(38, 61),
(96, 36),
(36, 40),
(99, 83),
(74, 76),
]
Run Code Online (Sandbox Code Playgroud)
使用target和values,方法应该产生答案(74, 76).
编辑
def distance(item, target):
return ((item[0] - target[0]) ** 2 + (item[1] - target[1]) ** 2) ** 0.5
best = min(values, key=lambda x: distance(x, target))
Run Code Online (Sandbox Code Playgroud)
这是笛卡尔距离问题.
x减去最佳x值.y减去最佳y值.min功能)将为您提供最佳选择.def distance(tup1,tup2):
"""
This question is unanswerable unless you can specify this
examples for 2d (you can write more general N-dimensional code if you need):
cartesian: math.sqrt((tup2[0]-tup1[0])**2 + (tup2[1]-tup1[1])**2)
manhattan: (tup2[0]-tup1[0]) + (tup2[1]-tup1[1])
"""
return # YOUR CODE HERE
min(values, key=lambda x:distance(target,x))
Run Code Online (Sandbox Code Playgroud)