【发布时间】:2022-01-22 00:43:27
【问题描述】:
我有这个数组
x = [2 6 2 6 1 2 6 1]
为x中的每个元素找到与数组中元素值相同的最大索引
x[:the index of the element]
它应该返回[- - 0 1 - 2 3 4]
如果没有这样的索引,用元素的相同索引填充它。
最终返回是[0 1 0 1 4 2 3 4]
我不允许使用循环。
【问题讨论】:
-
你对这个任务有什么问题?
我有这个数组
x = [2 6 2 6 1 2 6 1]
为x中的每个元素找到与数组中元素值相同的最大索引
x[:the index of the element]
它应该返回[- - 0 1 - 2 3 4]
如果没有这样的索引,用元素的相同索引填充它。
最终返回是[0 1 0 1 4 2 3 4]
我不允许使用循环。
【问题讨论】:
你的问题是numpy 的一个很好的小谜题。此解决方案不适用于数组中小于 1 的值(我不知道这是否有意义)
import numpy as np
x = np.array([2, 6, 2, 6, 1, 2, 6, 1])
# Find all indices for the elements in the array except the selfindex
a = x * np.tri(len(x), k=-1) == x[:, None]
# [[False False False False False False False False]
# [False False False False False False False False]
# [ True False False False False False False False]
# [False True False False False False False False]
# [False False False False False False False False]
# [ True False True False False False False False]
# [False True False True False False False False]
# [False False False False True False False False]]
# choose the last index (right side argmax) if the row contains any index else the selfindex
np.where(a.any(1), a.cumsum(1).argmax(1), np.arange(len(x)))
输出
array([0, 1, 0, 1, 4, 2, 3, 4])
【讨论】: