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

如何根据list1的索引将list2中的元素替换为对应子列表?

嵌套列表索引替换为对应子列表

原数据

list1 = [['a','b','c'],
         ['d','e','f'],
         ['g','h','d'],
         ['n','m','j']]

list2 = [[0,2],
         [1,3]]

解决方案

使用Python嵌套列表推导式可快速实现需求:

# 生成目标嵌套列表
result = [[list1[idx] for idx in sublist] for sublist in list2]

验证输出

执行代码后,result的结果与预期一致:

print(result)
# 输出:
# [[['a', 'b', 'c'], ['g', 'h', 'd']], [['d', 'e', 'f'], ['n', 'm', 'j']]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:05:22