繁体   English   中英

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

[英]find maximum value in array with excluded indices

在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM