You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表查找重复元素最右侧索引替代从左到右匹配的问题

问题解决方法
  • 原代码使用的list.index()方法默认从左向右检索,仅返回元素第一次出现的索引,无法匹配你需要的最右索引需求。
  • 额外注意:set是无序容器,直接转列表得到的affectedCoordinates顺序不固定,若需要固定和示例一致的升序排列,建议加sorted()保证顺序稳定。

解决方案

将循环内的index方法替换为Python列表内置的rindex()方法即可,该方法会从列表尾部开始检索,返回元素最后一次出现的索引。

修改后完整代码:

initialDictionary = {
    "xCoordinate": [2, 4, 6, 3, 6],
    "state": [1, 1, 1, 1, 0]
}

# 加sorted保证去重后顺序稳定为升序,和示例结果顺序一致
affectedCoordinates = sorted(set(initialDictionary["xCoordinate"]))
print(initialDictionary["xCoordinate"])
print(affectedCoordinates)

for affectedCoordinate in affectedCoordinates:
    if affectedCoordinate in initialDictionary["xCoordinate"]:
        # 替换为rindex取最右索引
        print(initialDictionary["xCoordinate"].rindex(affectedCoordinate))

运行输出:

[2, 4, 6, 3, 6]
[2, 3, 4, 6]
0
3
1
4

完全符合预期结果。

内容的提问来源于stack exchange,提问作者realFishSam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:18:05