栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

对具有多个值和权重的项目进行排名的最快方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对具有多个值和权重的项目进行排名的最快方法

您无法获得线性时间,但可以更快地完成。对我来说,这看起来像是一个矩阵乘法,所以我建议您使用

numpy

import numpy as npkeys = ['key1', 'key2', 'key3']values = np.matrix([    [1.1, 1.2, 1.3, 1.4],    [2.1, 2.2, 2.3, 2.4],    [3.1, 3.2, 3.3, 3.4]])weights = np.matrix([[10., 20., 30., 40.]]).transpose()res = (values * weights).transpose().tolist()[0]items = zip(res, keys)items.sort(reverse=True)

这使

[(330.0, 'key3'), (230.0, 'key2'), (130.0, 'key1')]

编辑: 有感谢@Ondro为np.dot并以@unutbu为np.argsort,这里是numpy的完全的改进版本:

import numpy as np# set up valueskeys = np.array(['key1', 'key2', 'key3'])values = np.array([    [1.1, 1.2, 1.3, 1.4],    # values1_x    [2.1, 2.2, 2.3, 2.4],    # values2_x    [3.1, 3.2, 3.3, 3.4]     # values3_x])weights = np.array([10., 20., 30., 40.])# crunch the numbersres = np.dot(values, -weights)   # negative of weights!order = res.argsort(axis=0)  # sorting on negative value gives       # same order as reverse-sort; there does       # not seem to be any way to reverse-sort       # directlysortedkeys = keys[order].tolist()

结果是

['key3', 'key2', 'key1']



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号