有效地对列表中的元素进行加权计数

时间:2012-05-02 20:31:15

标签: python algorithm

所以我有一个python dict,如:

 1:[ "red","blue","green"]
 2: ["blue","blue","red"]..

等等。

然后我有另一个python dict: score_dict = {

 pid: weight
 1: 2
 2: 20
 ...
}

所以,我想要的是...... 在第一个字典中,计算两种颜色一起出现的次数。 等等。 但是这个数量乘以它们的重量。

例如:

我想知道在此列表中出现红色和蓝色的次数:

所以对于pid 1    红色和蓝色发生一次。

 so this is (1*2) # 2 comes from the score_dict as pid1 has a weight 2

然后是第二次

我可以形成两个蓝色,红色对

so this is (1*20) + (1*20)

因此,蓝色和红色共同出现的总分为2 + 20 + 20 = 42

另外,我如何将其扩展为3种颜色?

如果我必须找到“红色”“蓝色”和“绿色”一起出现?

2 个答案:

答案 0 :(得分:4)

from collections import Counter

dict1 = {1:[ "red","blue","green"], 2: ["blue","blue","red"]}

weight = {1: 2, 2: 20}

score = 0

for k,v in dict1.iteritems():
    score += weight[k] * Counter(v)["red"] * Counter(v)["blue"]

结果:

>>> score
42

我的代码的最后一部分可以重写为生成器理解:

score = sum(weight[k] * Counter(v)["red"] * Counter(v)["blue"] for k,v in dict1.iteritems())

答案 1 :(得分:2)

不确定我是否完全理解,但这是一个想法:'

from collections import Counter

data = {
    1: ['red','blue','green'],
    2: ['blue','blue','red'],
}

weights = {
    1: 2,
    2: 20,
}

for k, v in data.items():
    score = sum([c * weights[k] for c in Counter(v).values()])
    print "so this is: %s val = %d" % (k, score)