3 回答

TA貢獻1871條經驗 獲得超8個贊
根據輸出,我認為你想要連續非零序列的第一個索引。
至于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)

TA貢獻1872條經驗 獲得超4個贊
還有一個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],請閱讀更多關于np.diff),然后我們需要添加第一個非零元素以及其中的所有值差異大于 1)
筆記:
它也適用于數組以非零元素或全部非零元素開頭的情況。

TA貢獻1810條經驗 獲得超4個贊
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())
添加回答
舉報