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

求助:如何生成对应列表元素首次出现索引的重复索引列表?

问题解决方法

原代码错误分析

你写的代码核心问题是混淆了列表元素的值和结果列表的索引:

  • 你把当前元素的值(比如3、6、8)当成了结果列表z_pts的下标去赋值,比如当z_rows[k] = 3时,你修改的是z_pts[3] = k,但实际需要的是给当前位置k的z_pts[k]赋值为该元素首次出现的索引。这直接导致结果完全错位。

正确解法

方法一:用字典记录首次出现索引(直观易懂)

Mylist = [3, 3, 6, 6, 6, 8, 8]
first_index = {}
expect = []
for idx, num in enumerate(Mylist):
    # 只记录每个元素第一次出现的索引
    if num not in first_index:
        first_index[num] = idx
    # 把当前元素对应的首次索引加入结果列表
    expect.append(first_index[num])

print(expect)  # 输出: [0, 0, 2, 2, 2, 5, 5]

方法二:用setdefault简化字典赋值

Mylist = [3, 3, 6, 6, 6, 8, 8]
first_index = {}
# 遍历一次记录所有元素的首次索引
for idx, num in enumerate(Mylist):
    first_index.setdefault(num, idx)
# 生成结果列表
expect = [first_index[num] for num in Mylist]

print(expect)  # 输出: [0, 0, 2, 2, 2, 5, 5]

方法三:原地修改列表(节省内存)

如果不需要保留原列表,可以直接原地修改:

Mylist = [3, 3, 6, 6, 6, 8, 8]
first_index = {}
for idx in range(len(Mylist)):
    num = Mylist[idx]
    if num not in first_index:
        first_index[num] = idx
    Mylist[idx] = first_index[num]

print(Mylist)  # 输出: [0, 0, 2, 2, 2, 5, 5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:03:25