2013-06-26 55 views
2
Test Array = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2] 

我需要遍歷數組以便首次查找3個連續條目是< 0.5,並返回此出現的索引。通過查看多個值的數組遍歷數組

Test Array = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2] 
         ^ ^^^
(indices) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
           ^

因此本次測試陣列內正在尋找索引/值是6

除了提議的解決方案,這將是很好的瞭解得到返回什麼值,如果「3個連續值< 0.5 '條件沒有得到滿足 - 它會不會沒有任何回報?或最後一個索引號?

(我想返回的值是0,如果條件不滿足)

+0

'http://stackoverflow.com/questions/176918/in-python-how-do-i-find-the-index-of-an-item-given-a-list-containing-it '這個鏈接可能會幫助你。 – pistal

回答

1

您可以使用zipenumerate

def solve(lis, num): 
    for i, (x,y,z) in enumerate(zip(lis, lis[1:], lis[2:])): 
     if all(k < num for k in (x,y,z)): 
      return i 
    #default return value if none of the items matched the condition 
    return -1 #or use None 
...  

>>> lis = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2] 
>>> solve(lis, 0.5) 
6 
>>> solve(lis, 4) # for values >3 the answer is index 0, 
0     # so 0 shouldn't be the default return value. 
>>> solve(lis, .1) 
-1 

使用itertools.izip內存有效的解決方案。

+0

真棒,乾杯:) 我實際上使用你的第一個答案(預編輯),但顯然有很多方法可以做到這一點 –

+0

@PeteLavelle很高興幫助。 :)我認爲一個功能會更好,所以修改了原來的解決方案。 –

0
from itertools import groupby 
items = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2] 

def F(items, num, k): 
    # find first consecutive group < num of length k 
    groups = (list(g) for k, g in groupby(items, key=num.__gt__) if k) 
    return next((g[0] for g in groups if len(g) >= k), 0) 

>>> F(items, 0.5, 3) 
0.1