2016-06-08 46 views
1

我有間隔的簡單列表:如何通過delta加入時間/ int間隔?

[ 
    { "begin" : 10, "end" : 20 }, 
    { "begin" : 1, "end" : 2 }, 
    { "begin" : 5, "end" : 7 }, 
    { "begin" : 100, "end" : 200 } 
] 

如何通過條件加入間隔

if abs(current["end"] - next["begin"] < 40) ? 

結果必然是:

[ 
    { "begin" : 1, "end" : 20 }, 
    { "begin" : 100, "end" : 200 } 
] 

我的解決辦法:

from pyinter import interval, IntervalSet 
def test(): 
    g = sorted(g, key=itemgetter("begin")) 
    ln = len(g) 
    if ln < 2: return 
    i = 0 
    while i < ln - 1: 
     if abs(g[i]["end"] - g[i+1]["begin"]) < 40: 
      g[i]["end"] = g[i+1]["begin"] 
     i = i + 1 

    a = IntervalSet() 
    for i in range(len(g)): 
     a.add(interval.closed(g[i]["begin"], g[i]["end"])) 

    res = [] 
    for key in a: 
     res.append({ "begin" : key.lower_value, "end" : key.upper_value }) 
    return res 

,但它是一個非常醜陋的

+0

如果什麼有重疊? –

+0

問題和結果不清楚,令人困惑! – tnanoba

回答

1

這個怎麼樣,

list_dicts = [ {"begin" : 10, "end" : 20 }, 
       {"begin" : 1, "end" : 2 }, 
       {"begin" : 5, "end" : 7 }, 
       {"begin" : 100, "end" : 200 }] 

# sorted by d['begin'] 
ld = sorted(list_dicts, key=lambda d:d['begin']) 

# merge 
results = [ld[0]] 
for idx, d in enumerate(ld[1:], 1): 
    if abs(d['begin'] - results[-1]['end']) < 40: 
     results[-1]['end'] = d['end'] 
    else: 
     results.append(d) 


print(results) 
# Output 
[{'begin': 1, 'end': 20}, {'begin': 100, 'end': 200}]