1

所以我有一个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种颜色?

就像我必须找出一起出现的“红色”“蓝色”和“绿色”?

4

2 回答 2

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())
于 2012-05-02T20:54:38.063 回答
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)
于 2012-05-02T20:56:16.080 回答