查找列表中第一个非零项目的索引

时间:2020-10-13 07:20:29

标签: python python-3.x list

我有以下列表:

list_test = [0,0,0,1,0,2,5,4,0,0,5,5,3,0,0]

我想找到列表中所有不等于零的第一个数字的索引。

在这种情况下,输出应为:

output = [3,5,10]

有没有Python的方法可以做到这一点?

5 个答案:

答案 0 :(得分:2)

根据输出,我认为您想要连续非零序列的第一个索引。

对于 Pythonic ,我将其理解为列表生成器,而它的可读性差

# works with starting with non-zero element.
# list_test = [1, 0, 0, 1, 0, 2, 5, 4, 0, 0, 5, 5, 3, 0, 0]
list_test = [0, 0, 0, 1, 0, 2, 5, 4, 0, 0, 5, 5, 3, 0, 0]
output = [i for i in range(len(list_test)) if list_test[i] != 0 and (i == 0 or list_test[i - 1] == 0)]
print(output)

答案 1 :(得分:1)

还有一个基于numpy的解决方案:

import numpy as np
l = np.array([0,0,0,1,0,2,5,4,0,0,5,5,3,0,0])
non_zeros = np.where(l != 0)[0]
diff = np.diff(non_zeros)
np.append(non_zeros [0], non_zeros [1 + np.where(diff>=2)[0]])  # array([ 3,  5, 10], dtype=int64)
说明:

首先,找到非零位置,然后计算这些位置的对差(我们需要添加1,因为其out[i] = a[i+1] - a[i],详细了解How to get EditText value to TextView at the time of typing without button click in android [closed] ),然后我们需要添加非零的第一个元素,以及所有差异大于1的值)

注意:

它也适用于数组以非零元素或所有非零开头的情况。

答案 2 :(得分:0)

来自Link

l = [0,0,0,1,0,2,5,4,0,0,5,5,3,0,0]
v = {}
for i, x in enumerate(l):
    if x != 0 and x not in v:
        v[x] = i

答案 3 :(得分:0)

list_test = [0,0,0,1,0,2,5,4,0,0,5,5,3,0,0]
res = {}
for index, item in enumerate(list_test):
    if item > 0:
        res.setdefault(index, None)
print(res.keys())

答案 4 :(得分:0)

我不了解Pythonic的意思,但这是使用简单循环的答案:

list_test = [0,0,0,1,0,2,5,4,0,0,5,5,3,0,0]

out = []

if list_test[0] == 0:
    out.append(0)

for i in range(1, len(list_test)):
    if (list_test[i-1] == 0) and (list_test[i] != 0):
        out.append(i)

请毫不犹豫地精确理解“ Pythonic”的含义!