Reputation: 123
Say I have an array or a list, for example L as in the following. Now I want to pick out the k maximal elements out of L (here k = 4) such that none of the picked out elements repeats. The following code accomplishes picking out the maximal elements, but with repetitions. What do I have to change? I have tried a few variants with if-statements, also another inbuilt for-loop, but am unable at the moment to find something that works.
L = [2,4,4,5,3]
Y = np.zeros(5)
for j in range(4):
for i in range(len(L)):
M = max(L)
if L[i] == M:
Y[i] = M
L[i] = 0
break
print(L)
print(Y)
Output:
[2, 0, 0, 0, 0]
[0., 4., 4., 5., 3.]
I would like the order to stay the same, whilst also requiring the number of elements in the list/array to stay the same. So in this case, what I want in the end is the following output:
[0, 0, 0, 0, 0]
[2., 4., 0., 5., 3.]
Upvotes: 0
Views: 91
Reputation: 16916
To get the k
max values and their corresponding indices skipping the next duplicates you can use
L = np.array([2,4,4,5,3])
k = 4
idx, values = [], []
for i in np.argsort(-L):
if L[i] not in values:
values.append(L[i])
idx.append(i)
if len(idx) == k:
break
print (idx, values)
Output:
[3, 1, 4, 0] [5, 4, 3, 2]
Now to frame it as the expected you can use
result = np.zeros(len(L))
result[idx] = L[idx]
print (result)
Output:
[2. 4. 0. 5. 3.]
Upvotes: 1
Reputation: 26188
L = sorted(list(set([2, 4, 4, 5, 3])))[:K]
What this does:
Upvotes: 0