在具有排除索引的数组中查找最大值



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

max = numpy.max(list)

我还有一个索引列表,在寻找最大值时我不想包括这些索引。

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

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

我确信这个问题以前已经得到了回答,但我不确定如何搜索它。

谢谢。

您可以使用掩码数组:

>>> 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

您可以使用列表理解:

numpy.max([val for idx, val in enumerate(list) if idx not in exclude_indices])
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

最新更新