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

嵌套结构:字典内列表的同索引值提取方法问询

提取字典中特定索引值的简便方法

当然可以!完全不用重构整个数据结构,你直接遍历原字典就能轻松提取指定索引的数值,同时保留样本名称作为标识。下面分两种常见场景给出具体实现:

提取单个索引(比如索引[1])

用字典推导式就能快速生成结果,代码简洁高效:

# 你的原始数据字典
data = {
    'sample1': [0.052333365, 0.048546686, 0.037446034, ...],
    'sample2': [0.499261188, 0.569225594, 0.971341941, ...],
    'sample3': [3.015670427, 3.608257648, 3.060244617, ...]
}

target_index = 1
# 提取所有样本的索引[1]值
result = {sample_name: values[target_index] for sample_name, values in data.items()}

运行后result的结构如下:

{'sample1': 0.048546686, 'sample2': 0.569225594, 'sample3': 3.608257648}

提取多个索引(比如索引[1]和[5])

如果需要同时获取多个索引的数值,同样可以用字典推导式实现,还能按需选择结果格式:

方式1:结果为「样本名: [索引1值, 索引5值]」

target_indices = [1, 5]
result = {sample_name: [values[i] for i in target_indices] for sample_name, values in data.items()}

生成的结果示例:

{
    'sample1': [0.048546686, 0.014583427],
    'sample2': [0.569225594, 1.214003077],
    'sample3': [3.608257648, 2.889312783]
}

方式2:结果为「样本名: {索引1: 值, 索引5: 值}」

要是想更清晰地对应索引和数值,可以生成嵌套字典:

target_indices = [1, 5]
result = {sample_name: {i: values[i] for i in target_indices} for sample_name, values in data.items()}

结果示例:

{
    'sample1': {1: 0.048546686, 5: 0.014583427},
    'sample2': {1: 0.569225594, 5: 1.214003077},
    'sample3': {1: 3.608257648, 5: 2.889312783}
}

这种方法的优势

  • 无需重构整个二维列表,只在遍历过程中提取需要的数值,内存占用更低,尤其适合你这种包含470个样本的数据集
  • 代码简洁易读,直接基于原数据结构操作,没有额外的转换步骤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:38:15