【发布时间】:2012-04-03 20:36:45
【问题描述】:
我正在尝试编写一个函数,该函数将使用“最近邻”或“最近匹配”类型算法过滤元组列表(模拟内存数据库)。
我想知道执行此操作的最佳(即大多数 Pythonic)方法。下面的示例代码希望能说明我正在尝试做的事情。
datarows = [(10,2.0,3.4,100),
(11,2.0,5.4,120),
(17,12.9,42,123)]
filter_record = (9,1.9,2.9,99) # record that we are seeking to retrieve from 'database' (or nearest match)
weights = (1,1,1,1) # weights to approportion to each field in the filter
def get_nearest_neighbour(data, criteria, weights):
for each row in data:
# calculate 'distance metric' (e.g. simple differencing) and multiply by relevant weight
# determine the row which was either an exact match or was 'least dissimilar'
# return the match (or nearest match)
pass
if __name__ == '__main__':
result = get_nearest_neighbour(datarow, filter_record, weights)
print result
对于上面的sn-p,输出应该是:
(10,2.0,3.4,100)
因为它是传递给函数 get_nearest_neighbour() 的样本数据的“最近”。
那么我的问题是,实现 get_nearest_neighbour() 的最佳方式是什么?出于简洁等目的,假设我们只处理数值,并且我们使用的“距离度量”只是当前行中输入数据的算术减法。
【问题讨论】:
标签: python