从多个列表中识别相似的数字

时间:2020-05-13 17:05:24

标签: python-3.x list numpy pattern-matching

我有3个列表:

r=[0.611695403733703, 0.833193902333201, 1.09120811998494]
g=[0.300675698437847, 0.612539072191236, 1.18046695352626]
b=[0.00668849762984564, 0.611946522017357, 1.16778502636141]

我想计算最相似数字的平均值。在上面的示例中,r[0]g[1]b[1]非常相似(大约为0.61...)。如何识别这种模式?

2 个答案:

答案 0 :(得分:0)

使用列表理解力:

r=[0.611695403733703, 0.833193902333201, 1.09120811998494]
g=[0.300675698437847, 0.612539072191236, 1.18046695352626]
b=[0.00668849762984564, 0.611946522017357, 1.16778502636141]


rg = [ (idx_r, idx_g,r,g) if abs(rr-gg) < 0.001 else None 
      for idx_r,rr in enumerate(r) 
      for idx_g, gg in enumerate(g)]

rb = [ (idx_r, idx_b,r,b) if abs(rr-bb) < 0.001 else None 
      for idx_r,rr in enumerate(r) 
      for idx_b, bb in enumerate(b)]

gb = [ (idx_g, idx_b,g,b) if abs(gg-bb) < 0.001 else None 
      for idx_g,gg in enumerate(g) 
      for idx_b, bb in enumerate(b)]

print(filter(None,rg+rb+gb))

输出:

[(0, 1, [0.611695403733703, 0.833193902333201, 1.09120811998494], 
        [0.300675698437847, 0.612539072191236, 1.18046695352626]), 
 (0, 1, [0.611695403733703, 0.833193902333201, 1.09120811998494], 
        [0.00668849762984564, 0.611946522017357, 1.16778502636141]), 
 (1, 1, [0.300675698437847, 0.612539072191236, 1.18046695352626], 
        [0.00668849762984564, 0.611946522017357, 1.16778502636141])]

输出是1.列表中的索引,2.列表中的索引以及两个列表的元组。

答案 1 :(得分:0)

您正在寻找计算所有点集之间的距离。最好的方法是level=0

scipy.spatial.distance.cdist