【问题标题】:Python: Acessing index numbers within an if statement nested within a for loopPython:访问嵌套在 for 循环中的 if 语句中的索引号
【发布时间】:2012-10-08 18:38:10
【问题描述】:

我有一个从直线渐变派生的整数数组。该数组称为 sign_slope,如下所示:

sign_slope = array([-1, 1, -1, ..., -1, -1, -1])

我正在搜索数组中连续项为:1、-1 的情况 例如,您可以从上述 sign_slope 的输出中看到: sign_slope[1] = 1 和 sign_slope[2] = -1 这将是我想检测项目/索引号的许多案例中的第一个。在上述情况下,我希望代码输出与第 (n-1) 个索引对应的索引号数组或列表,即 sign_slope[1]。 我已经写了以下似乎有效的打印声明。但是,我不知道如何输出索引号而不是当前情况下的值并将它们附加到列表或将它们输入到数组中。

for n in range(0, len(sign_slope)):
    if sign_slope[n] < 0 and sign_slope[n - 1] > 0:
        print sign_slope[n - 1]
    else:
        print 0

先谢谢了,

凯恩

【问题讨论】:

    标签: python arrays if-statement for-loop


    【解决方案1】:

    在一系列指标上循环通常被认为是非常不符合标准的。它读起来很糟糕,掩盖了你真正想要做的事情。因此,查找子列表的更好解决方案是循环使用 enumerate() 内置函数来获取值旁边的索引。我们还可以提供更通用的解决方案,并使其成为易于使用的生成器。

    def find_sublists(seq, sublist):
        length = len(sublist)
        for index, value in enumerate(seq):
            if value == sublist[0] and seq[index:index+length] == sublist:
                yield index
    

    我们在这里做的是遍历列表,获取值与子列表开头匹配的索引。然后,我们检查列表的该段是否与我们的子列表匹配,如果匹配,我们yield 索引。这使我们能够快速找到列表中所有匹配的子列表。

    然后我们可以像这样使用它,使用 list 内置函数从生成器创建一个列表:

    >>> list(find_sublists([-1, 1, -1, -1, -1, 1, -1], [1, -1]))
    [1, 5]
    

    【讨论】:

    • 嗨 Lattyware。我喜欢您的解决方案,并认为它应该可以很好地完成工作。非常感谢,凯恩
    【解决方案2】:

    假设您的数组sign_slopenumpy 数组,您可以在不编写循环的情况下执行此操作:

    import numpy as np
    
    # some data
    sign_slope = np.array([-1, 1, -1, 1, 1, -1, -1])
    
    # compute the differences in s
    d = np.diff(sign_slope)
    
    # compute the indices of elements in d that are nonzero
    pos = np.where(d != 0)[0]
    
    # elements pos[i] and pos[i]+1 are the indices
    # of s that differ:
    print s[pos[i]], s[pos[i]+1]
    

    这是一个显示变量值的 ipython 会话:

    In [1]: import numpy as np
    
    In [2]: s = np.array([-1, 1, -1, 1, 1, -1, -1])
    
    In [3]: d = np.diff(s)
    
    In [4]: print d
    [ 2 -2  2  0 -2  0]
    
    In [5]: pos = np.where(d != 0)[0]
    
    In [6]: print pos
    [0 1 2 4]
    
    In [7]: print s[pos[0]], s[pos[0]+1]
    -1 1
    
    In [8]: print s[pos[1]], s[pos[1]+1]
    1 -1
    
    In [9]: print s[pos[2]], s[pos[2]+1]
    -1 1
    
    In [10]: print s[pos[3]], s[pos[3]+1]
    1 -1
    

    希望对你有帮助

    编辑:实际上,回想起来,我遗漏了一些差异。我会回复你的。如有任何混淆,请见谅。

    编辑 2:已修复,我犯了一个愚蠢的错误。

    【讨论】:

    • 我也会试试这个 dmcdougall。非常感谢您的意见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    相关资源
    最近更新 更多