2013-06-26 48 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