【问题标题】:How to find indices for consecutive zeros at the end of the list?如何在列表末尾找到连续零的索引?
【发布时间】:2019-08-03 16:06:40
【问题描述】:

我有一个类似这样的列表,

test = [4, 7, 8, 9, 5, 0, 0, 0, 5, 0, 0, 0]

我想在列表末尾获取连续零的索引。我想要最后的起始索引为零或所有三个索引。检查我想要的输出。

期望的输出:

[9, 10, 11] (or) 9 (just 9 would also suffice)

我尝试了np.where,但它返回所有零的索引。

np.where((np.array(test)==0))

注意:我需要一个有效的解决方案,因为我的列表非常大。

【问题讨论】:

    标签: python python-3.x list numpy


    【解决方案1】:

    确认尾随零的模式后,我们可以使用基于数组和 NumPy 工具的方法,像这样 -

    len(test)-np.equal(test,0)[::-1].argmin()
    

    如果您在该索引之前需要全零索引 -

    In [100]: mask = np.equal(test,0)
    
    In [101]: idx = len(test)-mask[::-1].argmin()
    
    In [102]: np.flatnonzero(mask[:idx])
    Out[102]: array([5, 6, 7])
    

    为了解释索引获取部分,让我们将其分解为步骤 -

    # Mask of zeros
    In [100]: mask = np.equal(test,0)
    
    In [101]: mask
    Out[103]: 
    array([False, False, False, False, False,  True,  True,  True, False,
            True,  True,  True])
    
    # Flip it
    In [104]: mask[::-1]
    Out[104]: 
    array([ True,  True,  True, False,  True,  True,  True, False, False,
           False, False, False])
    
    # Get the first index of False ones, which would be the last non-zero
    # value from original array. Note that this is on flipped version of input
    In [105]: mask[::-1].argmin()
    Out[105]: 3
    
    # Get the original index position by subtracting from the length of it
    In [106]: len(test)-mask[::-1].argmin()
    Out[106]: 9
    

    【讨论】:

    • 谢谢。只是我没有在问题中添加的另一个小帮助。是否有可能在忽略最后三个连续的零之间获得零的索引。我正在寻找像[5, 6, 7] 这样的输出。
    • 你能告诉我这实际上是如何工作的吗?我的意思是np.equal(test,0)[::-1] 这会返回array([ True, True, True, False, True, True, True, False, False, False, False, False]),那么argmin 怎么会在这里返回3?它是如何用布尔数组决定最小值索引的。
    • @user_6396 在那里添加了一些解释。
    【解决方案2】:

    你可以做到的:

    test = [4, 7, 8, 9, 5, 0, 0, 0, 5, 0, 0, 0]
    
    res_index = 0
    
    for item in test[-1::-1]:
        if item == 0:
            res_index += 1
        else:
            break
    
    print(len(test) - res_index)
    

    【讨论】:

      【解决方案3】:

      这里是一个纯python几乎单线的解决方案,没有调用方法、建栈、创建列表等低效:

      >>> size = len(test)
      >>> while size > 0 and data[size-1] == 0: size -= 1
      

      然后你只需检索你的整数索引值

      >>> size
      9
      

      【讨论】:

      • NumPy 函数和数组在大数据上运行良好。当然,创建数组数据会产生开销。因此,当从另一端遍历并在附近寻找第一个非零值时,基于短路的方法可以从该场景中受益。我不知道您指的是building stacks, creating lists and all sort of inefficiencies 部分。
      • 我还是编辑了那部分,所以它不会伤害任何人。
      猜你喜欢
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2018-06-17
      相关资源
      最近更新 更多