找出给定条件的列表的最小和最大指数。

问题描述 投票:7回答:3

我有一个列表,比方说。

list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]

我想找出这个列表的最小和最大指数,其中: list_A > 0即在上面的例子中,它将是3和7。

对于其他单调增加的列表,我一直使用的是 np.searchsorted譬如 np.searchsorted(list,[0.5,1.0]) 找出其中的索引,其中列表是 between 0.5 and 1.0 分别。

但是,这种情况是完全不同的,而且 np.searchsorted 在这里不起作用,或者说我不知道它的作用方式是什么!

python list numpy indices
3个回答
6
投票

筛选压缩后的列表和它的指数,然后取最小和最大的指数。

>>> list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
>>> filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
>>> max(filtered_lst)
(7, 1.0)
>>> min(filtered_lst)
(3, 1.0)

如果你只需要索引,解压返回的值。

>>> maX,_ =  max(filtered_lst)
>>> maX
7

2
投票

另一种方法是使用 next():

list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]

print(next(idx for idx, item in enumerate(list_A) if item>0))
print(next(len(list_A)-1-idx for idx, item in enumerate(list_A[::-1]) if item>0))

产出

3
7

使用 next() 找到列表中的第一个项目 > 0 是一个优雅的解决方案。

要找到 最后的 单子 > 0 是比较棘手的这种方法。我使用的是 next() 来遍历并找到 第一> 0 在反向列表中使用 list_A[::-1]. 然后,我将生成的索引转换成正确的索引,将其从 len(list)-1,使用 len(list)-1-idx .


1
投票

您可以使用 np.where 函数来返回所有 elements > 0

In [116]: list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]

In [117]: arr = np.array(list_A)

In [118]: indx = np.where(arr > 0)[0]

In [119]: mini = indx[0]

In [120]: mini
Out[120]: 3

In [121]: maxi = indx[-1]

In [122]: maxi
Out[122]: 7
© www.soinside.com 2019 - 2024. All rights reserved.