我试图找出如何编写算法来以最有效的方式计算不同列表中的权重。我有一个包含各种ID的词典:
x["Y"]=[id1,id2,id3...]
x["X"]=[id2,id3....]
x["Z"]=[id3]
.
.
我对每个元素都有一个相关的权重:
w["Y"]=10
w["X"]=10
w["Z"]=5
输入说" Y"," Z"我想得到一个输出给我
(id1,10),(id2,10),(id3,15)
id3获得15,因为它在x [" Y"]和x [" Z"]
中都有有没有办法用矢量习惯来做到这一点?
答案 0 :(得分:2)
您可以使用itertools
库将列表中的常用术语组合在一起:
import itertools
import operator
a = {'x': [2,3], 'y': [1,2,3], 'z': [3]}
b = {'x': 10, 'y': 10, 'z': 5}
def matrix_weight(letter1,letter2):
final_list = []
for i in a[letter1]:
final_list.append((i, b[letter1]))
for i in a[letter2]:
final_list.append((i, b[letter2]))
# final_list = [(1,10), (2,10), (3,10), (3,5)]
it = itertools.groupby(final_list, operator.itemgetter(0))
for key, subiter in it:
yield key, sum(item[1] for item in subiter)
print list(matrix_weight('y', 'z'))
答案 1 :(得分:1)
我会在示例中使用字符串中的id
,但整数id的工作方式类似。
def id_weights(x, w, keys):
result = {}
for key in keys:
for id in x[key]:
if id not in result:
result[id] = 0
result[id] += w[key]
return [(id, result[id]) for id in sorted(result.keys())]
x = {"Y": ["id1","id2","id3"],
"X": ["id2", "id3"],
"Z": ["id3"]}
w = {"Y": 10, "X": 10, "Z": 5}
if __name__ == "__main__":
keys = ["Y", "Z"]
print id_weights(x, w, keys)
给出
[('id1', 10), ('id2', 10), ('id3', 15)]