Python:知识图谱中密度排名最高的 n 个三元组(二)
目录
一、需求
二、源码
三、效果
一、需求
- 给定一个列表,里边存放若干三元组,三元组可以看作空间中的点,求每个三元组与其他三元组之间的欧式距离之和,取平均值,作为此处三元组的密度,最终结果用一个字典来存储,键值是三元组,值是对应的密度,上节已完成:
(2条消息) Python:知识图谱中三元组的密度(一)_Starprog_UESTC_Ax的博客-CSDN博客https://angxiao.blog.csdn.net/article/details/123608002
- 将字典中的值从小到大排序,取前 n 名对应的键(即三元组),构成列表并返回。
二、源码
from scipy.spatial.distance import pdist, squareformdef order_score(dicts, count): """ 将字典中的值从小到大排序,取前count名对应的键,构成列表并返回 :param dicts: :param count: :return: """ # 字典根据value排序,获取value排名前count的key构成的列表 final_result = [] # 字典排序并取前count小的值,最终构成列表, final_value_result = sorted(dicts.values())[:count:] # 列表去重,因为要根据这些值来寻找对应的键值,避免寻找时重复添加键值 format_final_value_result = [] for id in final_value_result: if id not in format_final_value_result: format_final_value_result.append(id) # print(format_final_value_result) for item1 in format_final_value_result: for item2 in dicts.items(): if item2[1] == item1: final_result.append(item2[0]) return final_resultpoints = [(0, 0, 0), (2, 2, 2), (3, 3, 3), (1, 1, 1)]dis_resp = squareform(pdist(points))dis_avg = {} # 平均距离即密度词典flag = 0 # 标识是哪个三元组对应的距离for item in dis_resp: sum = 0 for i in item: sum += i dis_avg[points[flag]] = sum / (len(points) - 1) flag += 1print("每个三元组及在此处对应的密度构成的字典:\n%s" % dis_avg)print("密度最小的前n个三元组:\n%s" % order_score(dis_avg, 3))