-
ITMISS
根据输出,我认为你想要连续非零序列的第一个索引。至于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)
-
守着一只汪
还有一个numpy基于的解决方案:import numpy as npl = 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],请阅读更多关于np.diff),然后我们需要添加第一个非零元素以及其中的所有值差异大于 1)笔记:它也适用于数组以非零元素或全部非零元素开头的情况。
-
蝴蝶不菲
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())