2016-10-11 68 views
3

我只需要獲得某種程度上彼此遠離的元素/項目。例如,我有一個整數列表:過濾列表。僅在物品之間有一定距離的情況下獲取列表元素?

data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000] 

假設我想只提取具有具有至少彼此之間的距離的那些元素。 從上面的列表中,我需要輸出:

[-2000, 1000, 2000, 3500, 4500, 6000] 

我過濾這種方式:

filtered.append(data[0]) 
for index, obj in enumerate(data): 
    if index < (l - 1): 
     if abs(obj - data[index+1]) > 999: 
      filtered.append(data[index+1]) 

print(filtered) 

不希望輸出:

[-2000, 1000, 2000, 3500, 6000] 

它失敗,因爲它比較兩個相鄰的列表元素,irr儘管有些元素應該被過濾出來而不應該被考慮在內。

讓我更清楚地表現出來。
原始列表:[-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]

過濾過程:

-2000 - OK 
1000 - OK 
2000 - OK 
3500 - OK 
3800 - Out 
4500 - Should be OK, but it filtered out compared to 3800. But it should be compared to 3500 (not 3800 which is Out). 

如何解決呢?

回答

6

對數據進行排序,然後比較以前的會做到這一點:

data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000] 

lst = [min(data)]   # the min of data goes in solution list 
for i in sorted(data[1:]): 
    if i-lst[-1] > 999:  # comparing with last element 
    lst.append(i)   # of the solution list 

print (lst) 

輸出繼電器:

[-2000, 1000, 2000, 3500, 4500, 6000] 
相關問題