元组数组:基于权重返回唯一值(Python)

时间:2014-07-24 15:29:09

标签: python tuples unique

我已经在Python两个数组中压缩了

w
array([ 0.5 ,  1.  ,  0.5 ,  1.  ,  1.  ,  1.  ,  0.75,  1.  ])
index
array([ 218,  218, 1491, 2456, 1491, 1490,  250,  219])

test=zip(w,index)
test
[(0.5, 218), (1.0, 218), (0.5, 1491), (1.0, 2456), (1.0, 1491), (1.0, 1490), (0.75, 250), (1.0, 219)]

我希望返回一个新的元组列表,它只包含具有最高权重的唯一索引(即" index")。

换句话说,我想在这种情况下获得:

test2
[(1.0, 218), (1.0, 2456), (1.0, 1491), (1.0, 1490), (0.75, 250), (1.0, 219)]

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

d = {}
# Group the weights based on the indices
for wt, idx in test:
    d.setdefault(idx, []).append(wt)

# Create a new list with the max of weights and the index tuples
print [(max(d[idx]), idx) for idx in d]
# [(1.0, 1490), (1.0, 1491), (1.0, 2456), (0.75, 250), (1.0, 219), (1.0, 218)]