如何针对csr矩阵交叉检查字典的python列表

时间:2013-08-08 13:20:08

标签: python scipy

我有这个csr矩阵:

  (0, 12114) 4
  (0, 12001) 1
  (0, 11998) 2
  (0, 11132) 1
  (0, 10412) 7
  (1, 10096) 3
  (1, 10085) 1
  (1, 9105)  8
  (1, 8925)  5
  (1, 8660)  2
  (2, 6577)  2
  (2, 6491)  4
  (3, 6178)  8
  (3, 5286)  1
  (3, 5147)  7
  (3, 4466)  3

这个词典列表:

[{11998: 0.27257158100079237, 12114: 0.27024630707640002}, 

{10085: 0.23909781233007368, 9105: 0.57533007741289421}, 

{6577: 0.45085059256989168, 6491: 0.5895717192325539}, 

{5286: 0.4482789582819417, 6178: 0.32295433881928487}]

我想找到一种方法来搜索列表中的每个字典与矩阵中的相应行(例如,第0行针对第一个字典),并用字符中的值替换字典中的每个值,关键...

结果将是:

[{11998: 2, 12114: 4},
 {10085: 1, 9105: 8},  
 {6577: 2, 6491: 4}, 
 {5286: 1, 6178: 8}]

1 个答案:

答案 0 :(得分:2)

如果X是您的稀疏矩阵并且

D = [{11998: 0.27257158100079237, 12114: 0.27024630707640002}, 
     {10085: 0.23909781233007368, 9105: 0.57533007741289421}, 
     {6577: 0.45085059256989168, 6491: 0.5895717192325539}, 
     {5286: 0.4482789582819417, 6178: 0.32295433881928487}]

然后

for i, d in enumerate(D):
    for j in d:
        d[j] = X[i, j]

给出了期望的结果:

>>> D
[{12114: 4.0, 11998: 2.0}, {9105: 8.0, 10085: 1.0}, {6577: 2.0, 6491: 4.0}, {6178: 8.0, 5286: 1.0}]