[英]Python - Finding indices of the first non-zero element to the left for each element
[英]Finding indices of first non-zero items in a list
我有以下清單:
list_test = [0,0,0,1,0,2,5,4,0,0,5,5,3,0,0]
我想找到列表中所有不等於零的第一個數字的索引。
在這種情況下,輸出應該是:
output = [3,5,10]
有沒有 Pythonic 的方法來做到這一點?
根據輸出,我認為您需要連續非零序列的第一個索引。
至於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 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 的值)
它也適用於數組以非零元素或所有非零元素開頭的情況。
從鏈接。
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
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())
我不知道你所說的 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”是什么意思!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.