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

如何快速将四个列表转为以组合索引为键的Python字典?

Python:快速将两组索引与元素列表组合成指定字典

问题输入

给定四个列表:

list_a = ['hello', 'yes', 'you']
list_a_ind = [0, 1, 2]
list_b = ['he', 'here', 'great'] 
list_b_ind = [1, 2, 3]

预期输出

需要生成以下格式的字典,以对应位置的索引元组为键,元素元组为值:

dictionary_ab = {(0,1): ('hello', 'he'), 
                 (1,2): ('yes', 'here'), 
                 (2,3): ('you', 'great')}

最快实现方法

利用Python内置的zip和dict函数是最高效的方式——这些函数基于底层C实现,比手动循环的执行速度快得多。

方法一(最简洁)

直接将索引对和元素对分别打包后,再转换为字典:

dictionary_ab = dict(zip(zip(list_a_ind, list_b_ind), zip(list_a, list_b)))

方法二(可读性更强)

用字典推导式,逻辑更直观:

dictionary_ab = {(a_idx, b_idx): (a_val, b_val) 
                 for a_idx, a_val, b_idx, b_val in zip(list_a_ind, list_a, list_b_ind, list_b)}

两种方法的执行效率几乎一致,都能在O(n)时间复杂度内完成(n为列表长度),是处理这类需求的最优解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:50:26