2016-08-25 17 views
1

我是新來的python和嘗試了很多後,我無法找到解決方案,以解決以下問題。python:如何從列表中選擇具體值

我有列表(下面),並希望找到元素的索引號,只要它們是連續的,除了1個單獨的零。 即從下面的列表-7, -8, -4不應被挑選,因爲它們之間存在更多的零差距。 但元素的以下指標數量應挑選

-6, 0, -4, -29, -10, 0, -16 

2, 3, 0, 18, -1, -2 

21, 10, -10, 0, -12, 0 

deltacount = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, 
    **-6, 0, -4, -29, -10, 0, -16**, 0, 0, 
    **2, 3, 0, 18, -1, -2**, 0, 0, 0, 0, 0, 0, 
    **21, 10, -10, 0, -12, 0**] 

請幫助。

+0

你能更詳細地說明條件嗎? –

+0

我想基本上創建一個分組,即如果列表中的元素後面沒有兩個零,並且前面的兩個值也不是零,那麼我想將它包括在組中。所以從上面的列表中將會有三個組標記爲粗體,我只是希望他們的索引位置在列表中。 – user1672315

回答

0
deltacount = [0,-7, 0, 0,-8, 0, 0,-4, 0,0,0,-6,0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 0] 
zero_before_count=0 
zer_after_count=0 
indx=0 
list1=[] 
for i in deltacount: 
    if i!=0: 
     indx=deltacount.index(i) 
     if deltacount[indx-1]==0 and deltacount[indx-2]==0: 
      if deltacount[indx+1]==0 and deltacount[indx+2]==0: 
       list1.append(i) 
finallist=[x for x in deltacount if x not in list1 and x!=0] 
print finallist 

試試看看這個代碼。

+0

謝謝你的幫助。還有兩個問題。不知何故-4在6,0,-4,-29,-10,0,-16組中缺失,我怎樣才能得到finallist中的索引位置? – user1672315