在排除索引的情况下查找数组中的最大值

5

在Python中,我有一个由10个数字组成的列表。我知道可以通过以下方式找到列表中的最大值:

max = numpy.max(list)

我还有一个索引列表,当寻找最大值时不想包含在内。

i.e. exclude_indices = [2,3,7]

我想在数字列表中搜索不在2、3或7索引处的最大值。

我相信这个问题以前已经被回答过了,但我不知道该如何搜索。

谢谢。


2
它是一个list还是一个np.array - jonrsharpe
在这种情况下,实际上是一个numpy数组。 - user1551817
相关链接:https://dev59.com/XGs05IYBdhLWcg3wIOfS - jonrsharpe
3个回答

6
你可以使用掩码数组来处理相关问题:
>>> arr = np.arange(10)
>>> indices = [2, 3, 9]
>>> mask = np.zeros(arr.size, dtype=bool)
>>> mask[indices] = True
>>> a = np.ma.array(arr, mask=mask)
>>> np.max(a)
8

2
np.zeros(arr.size, dtype=bool) 会更快。 - shx2

2

您可以使用列表推导式:

numpy.max([val for idx, val in enumerate(list) if idx not in exclude_indices])

1
这将排除而不是索引 - jonrsharpe
你应该在这里使用Python的max()函数,它会更快(仅当与ndarray一起使用时,np.max()才更好),并且内存效率更高,因为它可以使用生成器表达式。 - Ashwini Chaudhary

2
def max_exclude(lst, exclude):
    max_idx = None
    max_val = float('-inf')
    for (i,v) in enumerate(lst):
        if i in exclude: continue
        if v > max_val:
            max_val = v
            max_idx = i
    return (max_idx, max_val)

这不像使用列表推导式“筛选”列表那样简单,但它更高效,因为它不需要先创建列表的副本。
lst = [7, 8, 9, 2, 6, 5, 3, 1, 4]

print max_exclude(lst, [2,3,7])

# Prints "(1,8)"
#   1 is the index of the maximum
#   8 is the value of the maximum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接