【问题标题】:iterate through an array looking at multiple values遍历查看多个值的数组
【发布时间】:2013-06-23 11:10:41
【问题描述】:
Test Array = [1, 2, 3, 1, 0.4, 1, 0.1, 0.4, 0.3, 1, 2]

我需要遍历一个数组,以找到第一次 3 个连续条目

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)

【问题讨论】:

  • http://stackoverflow.com/questions/176918/in-python-how-do-i-find-the-index-of-an-item-given-a-list-containing-it此链接可能对您有所帮助。

标签: python arrays list loops compare


【解决方案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 获取内存高效解决方案。

【讨论】:

  • 太棒了,干杯 :) 我实际上使用了你的第一个答案(预编辑),但显然有很多方法可以做到这一点
  • @PeteLavelle 很高兴有帮助。 :) 我认为一个函数会更好,所以修改了原来的解决方案。
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2015-10-20
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多