【问题标题】:Array of tuples: return unique values based on weights (Python)元组数组:根据权重返回唯一值(Python)
【发布时间】:2014-07-24 15:29:08
【问题描述】:

我在 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)]

我想返回一个新的元组列表,它只包含权重最高的唯一索引(即“索引”)。

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

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

有什么想法吗?

【问题讨论】:

    标签: python tuples unique


    【解决方案1】:
    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)]
    

    【讨论】:

      猜你喜欢
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2018-05-17
      • 2014-04-27
      • 2019-08-16
      相关资源
      最近更新 更多