2015-12-12 55 views
0

好的,我有一個列表,它們是整數列表。一些兒童名單只是[0],這是一件好事。我喜歡這些[0]的和我需要每個元素!= [0]之間至少有一個[0]。我一直在努力處理這些for循環,if語句和python的any()函數以創建下面看到的混亂,雖然它沒有提供任何錯誤,但它根本行不通。它沒有改變。有沒有人有如何解決這個問題的建議?相對於其他元素測試特定元素的位置python

for r in range(0,len(combinations)): 
     if any((combinations[r][e] != [0]) and (combinations[r][e-1] != [0]) and (combinations[r][e+1] != [0]) for e in range(1,len(combinations[r])-1)): 
      del combination[r] 

下面我添加了一個典型的combinations列表的例子。

[([1, 1], [0], [1, 1], [0]), 
([1, 1], [0], [0], [1, 1]), 
([1, 1], [1, 1], [0], [0]), 
([1, 1], [1, 1], [0], [0]), 
([1, 1], [0], [0], [1, 1]), 
([1, 1], [0], [1, 1], [0])] 

下面是我想結束的那種數據。

[([1, 1], [0], [1, 1], [0]), 
([1, 1], [0], [0], [1, 1]), 
([1, 1], [0], [0], [1, 1]), 
([1, 1], [0], [1, 1], [0])] 

你可以看到,在彼此相鄰!= [0]元素的父列表中的兩個列表已刪除,因爲沒有它們之間的[0]。任何想法如何實現這一目標?

回答

2
combinations = [([1, 1], [0], [1, 1], [0]), 
      ([1, 1], [0], [0], [1, 1]), 
      ([1, 1], [1, 1], [0], [0]), 
      ([1, 1], [1, 1], [0], [0]), 
      ([1, 1], [0], [0], [1, 1]), 
      ([1, 1], [0], [1, 1], [0])] 

def filterComb(comb): 
    result = list() 
    for current in comb: 
     isok = True 
     for i in range(1, len(current)): 
      if current[i] != [0] and current[i-1] != [0]: 
       isok = False 
       break 
     if isok: 
      result.append(current) 
    return result 

combinations = filterComb(combinations) 
+0

哇!這是令人難以置信!這個''''操作符到底是什麼? –

+1

這只是一個相當於!= –

+1

我會說總是使用'!='。由於'<>'不清楚,並且自Python 3.x以來它已被刪除。 –

相關問題