2012-10-18 36 views
1

我有一個從行的漸變派生的整數數組。該數組被稱爲sign_slope,看起來像這樣:Python:訪問嵌套在for循環中的if語句中的索引號

sign_slope = array([-1, 1, -1, ..., -1, -1, -1]) 

我正在尋找的情況下,從而在陣列內連續的項目有:1,-1 例如,你可以從sign_slope以上輸出看到: sign_slope [1] = 1和sign_slope [2] = -1 這將是我想檢測項目/索引編號的第一個例子。我希望代碼輸出一個對應於第(n-1)號指數的數組或索引號列表,即在上述情況下的sign_slope [1]。 我已經寫了下面的打印語句似乎工作。但是,我不知道如何輸出索引號而不是當前的值,並將它們附加到列表中或將它們輸入到數組中。

for n in range(0, len(sign_slope)): 
    if sign_slope[n] < 0 and sign_slope[n - 1] > 0: 
     print sign_slope[n - 1] 
    else: 
     print 0 

由於是預先

凱恩

+2

index = n所以,'print n' – lucemia

回答

4

循環在一定範圍的indicies的通常被認爲是非常unpythonic。它讀得很差,掩蓋了你真正想要做的事情。因此,尋找您的子列表的更好的解決方案是循環使用內建的enumerate()以獲得與這些值一致的指示。我們還可以提供更通用的解決方案,並使其成爲一種易於使用的生成器。

def find_sublists(seq, sublist): 
    length = len(sublist) 
    for index, value in enumerate(seq): 
     if value == sublist[0] and seq[index:index+length] == sublist: 
      yield index 

我們在這裏做的是循環通過列表,取其中值我們的子表的開始相匹配的indicies。然後我們檢查該列表是否與我們的子列表匹配,如果匹配,我們yield索引。這使我們能夠快速找到列表中的所有匹配的子列表。

然後我們就可以使用這個像這樣,使用list內建創造了發電機清單:

>>> list(find_sublists([-1, 1, -1, -1, -1, 1, -1], [1, -1])) 
[1, 5] 
+0

Hi Lattyware。我喜歡你的解決方案,並認爲它應該很好地完成這項工作。感謝堆,凱恩 – tripkane

0

你可以做到這一點,而無需編寫一個循環,假設你的陣列sign_slopenumpy數組:

import numpy as np 

# some data 
sign_slope = np.array([-1, 1, -1, 1, 1, -1, -1]) 

# compute the differences in s 
d = np.diff(sign_slope) 

# compute the indices of elements in d that are nonzero 
pos = np.where(d != 0)[0] 

# elements pos[i] and pos[i]+1 are the indices 
# of s that differ: 
print s[pos[i]], s[pos[i]+1] 

這裏的顯示變量的值的IPython的會話:

In [1]: import numpy as np 

In [2]: s = np.array([-1, 1, -1, 1, 1, -1, -1]) 

In [3]: d = np.diff(s) 

In [4]: print d 
[ 2 -2 2 0 -2 0] 

In [5]: pos = np.where(d != 0)[0] 

In [6]: print pos 
[0 1 2 4] 

In [7]: print s[pos[0]], s[pos[0]+1] 
-1 1 

In [8]: print s[pos[1]], s[pos[1]+1] 
1 -1 

In [9]: print s[pos[2]], s[pos[2]+1] 
-1 1 

In [10]: print s[pos[3]], s[pos[3]+1] 
1 -1 

希望這會有所幫助

編輯:其實,回想起來,我錯過了一些差異。我會盡快回復你。對不起,有任何困惑。

編輯2:修正,我犯了一個愚蠢的錯誤。

+0

將嘗試這個以及dmcdougall。非常感謝輸入。 – tripkane