简体   繁体   中英

Pick out k maximal elements of a array/list

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

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.]
L = sorted(list(set([2, 4, 4, 5, 3])))[:K]

What this does:

  • creates a set from the list of elements. A set is a collection with only unique elements
  • turns the set into a list so we can sort it
  • sorts the list
  • [:K] takes the last K elements from the list

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