迭代查看多个值的数组

时间:2013-06-26 10:44:37

标签: python arrays list loops compare

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

除了提出的解决方案之外,如果连续的&lt; 0.5&#39;连续值<0.5,那么知道返回什么值将是一件好事。条件不满足 - 它只是简单地返回什么?还是最后一个索引号?

(如果条件不满足,我希望返回的值为0)

2 个答案:

答案 0 :(得分: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进行内存有效解决方案。

答案 1 :(得分: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
相关问题