gpt4 book ai didi

python - 遍历数组查看多个值

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:28 25 4
gpt4 key购买 nike

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)

最佳答案

您可以使用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 实现内存高效解决方案。

关于python - 遍历数组查看多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17317928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com