2017-03-02 112 views
2

我想檢查範圍的名單是在接下來的列表的範圍,這裏有一個例子:檢查清單範圍是在另一個列表範圍

pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]] 

正如我們所看到的,在pos[0]處於pos[1][50, 100]包含在[50, 200]中)的範圍內,pos[2]pos[3]pos[4]pos[5]相同。

要做到這一點,我創建了一個返回boolean值的函數:

def in_list(i): # index of the list 
    if i < len(pos)-2 and pos[i][0] >= pos[i+1][0] and pos[i][0] <= pos[i+1][1] 
    and pos[i][1] >= pos[i+1][0] and pos[i][1] <= pos[i+1][1]: 
     return True 
    else: 
     return False 

它看起來這麼難看,任何人可以提出另一種解決辦法?

編輯:

由於@MKesper的建議,我也應該遍歷使用循環列表條目(和可能得到的名單真/假每個位置)。

+1

你可能想用'for pos in pos:' – MKesper

+0

@MKesper遍歷你的列表條目,是的,你是對的。 – Bilal

回答

5

你知道的範圍[a,b]是在給定的c <= ab <= d一系列[c,d](所以a,bc,dc <= a < b <= d之間,但我們假設a < b反正總是成立)。所以,你可以簡單地使用:

def in_list(pos,i): 
    a,b = pos[i] 
    c,d = pos[i+1] 
    return c <= a and b <= d 

如果您要檢查有任何這種情況下,你可以使用:其轉移副本

any(in_list(pos,i) for i in range(len(pos)-1)) 
+0

也許你也可以讓'pos'成爲函數的參數。這不是真的要求,但訪問全局並不是一個好習慣。 – MSeifert

+0

@ MSeifert:的確如此。因爲在原來的問題中,「pos」的範圍太廣泛了。 –

+0

@WillemVanOnsem謝謝,但爲什麼'in(in_list(pos,2)for range(len(pos)-1))'返回'False'? – Bilal

3

郵編/交錯列表,然後檢查以前的項目包含在該範圍內。

一個襯裏來計算在所有元素:

pos = [[50, 100], [50, 200], [250, 1500], [300, 2000], [300, 3300]] 

result = [all(x1 <= a <= y1 for a in t) for t,(x1,y1) in zip(pos,pos[1:])] 


print(result) 

結果:

[True, False, False, True] 

(結果具有1少當然項:最後一個項目沒有資格/未測試)

也許all是矯枉過正,因爲只有2個值可以測試,所以備選方案可能是:

result = [x1 <= x0 <= y1 and x1 <= y0 <= y1 for (x0,y0),(x1,y1) in zip(pos,pos[1:])] 
+0

我喜歡單線隊員(我通常不太喜歡他們),這很難理解。不過,這可能很快。 – MSeifert

+0

我的選擇可能會更好,因爲它不使用'all':少一個gencomp –