Given a list of employees' scores. the employee with the highest score among the first k employees or the last k employees in the score list is selected. then removed from the list.
I want to get the real index for the selected element.
score=[5, 12, 15, 11, 15]
k=2
max_value = max(max(score[:k]), max(score[-k:]))
index=score.index(max_value)
print(index)
score.remove(score[index])
print(score)
the output is :
2
[5, 12, 11, 15]
the desired output:
4
[5,12,15,11]
The problem is index() will return the first occurrence. I know enumerate can be a solution somehow, but I am not able to apply it in my code.
CodePudding user response:
Seems like You want to remove the last highest value from the list
You'll need to find all indices of the max value, then just use the last index to remove the item from the list:
max_val_indices = [i for i, x in enumerate(score) if x == max(score)] # max_val_indices = [2, 4]
score.remove(max_val_indices) # score = [5,12,15,11]
print(max_val_indices[-1:], score) # desired output: 4 [5,12,15,11]
One-liner:
score.remove([i for i, x in enumerate(score) if x == max(score)][-1:]) # score = [5,12,15,11]
CodePudding user response:
Thank for editing your question. I think I now understood what you want. Of course this can be shorten by removing some variables. I left them there to make the code more clear.
score = [5, 15, 12, 15, 13, 11, 15]
k = 2
first = score[:k]
last = score[-k:]
cut = [*first, *last]
max_value = max(cut)
for i in range(len(score)):
if (i < k or i >= len(score)-k) and score[i] == max_value:
score.pop(i)
break
print(score)