2014-04-11 48 views
1

考慮範圍的以下數組:如何組合最接近的非重疊範圍?

a = [ 
    [2665.189, 2805.362], 
    [1304.812, 1429.328], 
    [2859.97, 2913.514], 
    [2931.631, 3597.11], 
    [158.045, 172.058], 
    [918.479, 929.199], 
    [263.246, 264.146], 
    [856.724, 860.121] 
] 

我想其中w另一範圍的最小值和最大值B /差相對於所考慮的範圍是小於或等於300 I,E

到範圍結合
[[2665.189, 2805.362],[2859.97, 2913.514],[2931.631, 3597.11]] 

2859.97 - 2805.365 = 54.6082931.631-2913.514 = 18.117之間的區別,所以現在變成一個範圍[2665.189, 3597.11]

所以合作像這樣的最終結果應該是:

a = [ 
[158.045, 264.146], 
[856.724, 929.199], 
[1304.812, 1429.328], 
[2665.189,3597.11] 
] 

如果任何人可以建議在python的代碼來做到這一點。這會有幫助嗎?

+0

是否有可能要重疊的範圍,還是總是不相交? –

+0

*你的代碼在哪裏?它的問題究竟是什麼? – jonrsharpe

+0

@ F.J範圍總是不重疊 – user3405360

回答

2

在這裏你去:

a = [[2665.189, 2805.362], [1304.812, 1429.328], [2859.97, 2913.514], [2931.631, 3597.11], [158.045, 172.058], [918.479, 929.199], [263.246, 264.146], [856.724, 860.121]] 

sorted_a = sorted(a, key=lambda x: x[0]) 
output_a = [sorted_a[0]] 
for idx, ele in enumerate(sorted_a[1:], 1): 
    if ele[0] - sorted_a[idx - 1][1] <= 300: 
     output_a[-1][1] = ele[1] 
    else: 
     output_a.append(ele) 

output_a現在有:

[[158.045, 264.146], 
[856.724, 929.199], 
[1304.812, 1429.328], 
[2665.189, 3597.11]] 
1

這裏是一個解決方案,而不是最優雅的一個,但工作:

RANGE_LIMIT = 300 

a = [[2665.189, 2805.362], [1304.812, 1429.328], [2859.97, 2913.514], [2931.631, 3597.11], [158.045, 172.058], [918.479, 929.199], [263.246, 264.146], [856.724, 860.121]] 
a = sorted(a) 
done = False 

while not done: 
    done = True 
    for r in range(len(a)-1): 
     if a[r] == []: continue 
     if((a[r+1][0] - a[r][1]) < RANGE_LIMIT): 
      a[r] = [a[r][0], a[r+1][1]] 
      a[r+1] = [] 
      done = False 
    a = [x for x in a if x] 

print a