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)

4

2 回答 2

1

You can use zip and enumerate:

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

Use itertools.izip for memory efficient solution.

于 2013-06-26T10:47:13.077 回答
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
于 2013-06-26T10:55:23.050 回答