在Python切片后,在列表中获取特定元素的索引
给出了员工分数清单。在最初的K员工或得分列表中的最后K雇员中得分最高的员工。然后从列表中删除。
我想获得所选元素的真实索引。
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)
输出为:
2
[5, 12, 11, 15]
所需的输出:
4
[5,12,15,11]
问题是index()将返回第一次出现。我知道枚举可以是一种解决方案,但我无法将其应用于我的代码中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎您想从列表中删除最后的最高值,
您需要找到最大值的所有索引,然后只使用最后一个索引从列表中删除该项目:
单线:
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:
One-liner:
感谢您编辑您的问题。我想我现在了解您想要什么。当然,可以通过删除一些变量来缩短这一点。我把它们留在那里,以使代码更加清晰。
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.