在Python切片后,在列表中获取特定元素的索引

发布于 2025-02-02 12:06:16 字数 428 浏览 3 评论 0原文

给出了员工分数清单。在最初的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与往事干杯 2025-02-09 12:06:16

似乎您想从列表中删除最后的最高值,

您需要找到最大值的所有索引,然后只使用最后一个索引从列表中删除该项目:

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]

单线:

score.remove([i for i, x in enumerate(score) if x == max(score)][-1:]) # score = [5,12,15,11]

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]
巷雨优美回忆 2025-02-09 12:06:16

感谢您编辑您的问题。我想我现在了解您想要什么。当然,可以通过删除一些变量来缩短这一点。我把它们留在那里,以使代码更加清晰。

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文