如何在列表末尾找到连续零的索引?

2024-05-12 20:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张这样的单子

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))

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


Tags: ortest列表np解决方案wherearray单子
3条回答

确认了尾随零的模式后,我们可以使用基于数组和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

你可以做到:

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)

这是一个纯python几乎一行程序的解决方案,没有调用方法、构建堆栈、创建列表和其他低效之处:

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

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

>>> size
9

相关问题 更多 >