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

如何从字典列表中根据指定键获取首个唯一值的索引

问题:字典列表中按指定键获取首个唯一值的索引

示例数据

l=[
    {"id":1, "score":80, "remarks":"B" },
    {"id":2, "score":80, "remarks":"A" },
    {"id":1, "score":80, "remarks":"C" },
    {"id":3, "score":80, "remarks":"B" },
    {"id":1, "score":80, "remarks":"F" },
]

需求说明

根据指定键,找到该键对应值首次出现的索引,预期结果如下:

using_id = [0,1,3]
using_score = [0]
using_remarks = [0,1,2,4]

遇到的问题

如果是普通数字列表,可通过一行代码实现需求:

indexes = [l.index(x) for x in sorted(set(l))]

但字典属于不可哈希类型,直接对字典列表使用set()会抛出错误:TypeError: unhashable type: 'dict'

约束条件

  • 仅使用Python3.10默认模块
  • 代码需支持处理数百条数据的列表
  • 代码行数越少越好

暴力解法(参考)

unique_items = []
unique_index = []

for index, item in enumerate(l, start=0):
    if item["remarks"] not in unique_items:
        unique_items.append(item["remarks"])
        unique_index.append(index)

print(unique_items)
print(unique_index)

优化解法

利用集合的O(1)查询特性,结合海象运算符简化代码,同时将时间复杂度从暴力解法的O(n²)优化为O(n):

可复用函数实现

def get_first_unique_indices(lst, key):
    seen = set()
    return [idx for idx, item in enumerate(lst) if (val := item[key]) not in seen and not seen.add(val)]

使用示例

using_id = get_first_unique_indices(l, "id")
using_score = get_first_unique_indices(l, "score")
using_remarks = get_first_unique_indices(l, "remarks")

print(using_id)    # 输出: [0, 1, 3]
print(using_score) # 输出: [0]
print(using_remarks) # 输出: [0, 1, 2, 4]

逻辑说明

  • 海象运算符:=在判断的同时提取键对应的值,减少重复取值操作
  • 集合seen记录已出现的值,保证每个值只保留首次出现的索引
  • seen.add(val)返回None,not seen.add(val)始终为True,用来在判断通过后完成添加操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:45:40