简体   繁体   中英

find maximum value in array with excluded indices

In Python, I have a list of 10 numbers. I know that I can find the maximum value in the list by doing something like:

max = numpy.max(list)

I also have a list of indices that I don't want to include when looking for the maximum value.

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

So I want to search for the maximum in the list of numbers that aren't at index 2,3 or 7.

I'm sure this has been answered before, but I'm not sure how to search for it.

Thanks.

You can use a masked array :

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

This isn't as simple as using a list comprehension to "filter" the list, but it is more efficient as it doesn't require creating a copy of the list first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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