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

如何为Python字典中的每个键生成idx与infeed_idx的元组

需求描述

给定如下Python字典(其中array为NumPy数组):

{4: {'idx': [45, 177, 181],
    'Baggage': array([ 13, 103,  87]),
    'infeed_idx': array([1, 3, 3])},
 7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
      'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16,  8]),
      'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])},
}

需要为字典中的每个键对应的子字典添加tuple_id字段,该字段是由对应位置的idx元素和infeed_idx元素组成的元组列表,预期输出如下:

{4: {'idx': [45, 177, 181],
    'Baggage': array([ 13, 103,  87]),
    'infeed_idx': array([1, 3, 3]),
    'tuple_id': [(45,1),(177,3),(181,3)]},
 7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
      'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16,  8]),
      'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2]),
      'tuple_id': [(62,1),(105,1),(173,1),(174,1),(186,1),(57,2),(74,2),(102,2),(115,2),(164,2)]}
}

(注:原预期输出中键4的tuple_id第三个元组存在笔误,已修正为(181,3))

Python实现代码

通过遍历字典的每个键值对,利用zip函数将对应位置的元素配对,生成元组列表后添加到子字典中即可实现需求:

import numpy as np

# 原始输入字典
baggage_dict = {
    4: {'idx': [45, 177, 181],
        'Baggage': np.array([13, 103, 87]),
        'infeed_idx': np.array([1, 3, 3])},
    7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
        'Baggage': np.array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
        'infeed_idx': np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])}
}

# 遍历生成tuple_id并添加到子字典
for key, sub_dict in baggage_dict.items():
    sub_dict['tuple_id'] = list(zip(sub_dict['idx'], sub_dict['infeed_idx']))

# 输出结果示例
for key in baggage_dict:
    print(f"{key}: {baggage_dict[key]}")

代码说明

  • zip(sub_dict['idx'], sub_dict['infeed_idx'])会将列表和NumPy数组中对应位置的元素一一配对,生成迭代器;
  • list()将迭代器转换为列表,得到所需的元组列表;
  • 直接在原字典的子字典中新增tuple_id字段,完成修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:10:36