Skip to main content
 首页 » 编程设计

python之遍历数组查看多个值

2025年05月04日7lori

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)

请您参考如下方法:

您可以使用zip 和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 

使用 itertools.izip 实现内存高效解决方案。