Python如何将list1元素作为索引取list2的值生成指定新列表
Python列表索引映射取值实现方案
需求说明
给定以下两个Python列表:
list1 = [[2, 4], [3], [0, 4], [1], [0, 2], []] list2 = [12000,24000,14000,22000,13000,30000]
需要将list1各子列表中的元素作为索引,取出list2对应位置的值替换原有索引,最终得到目标列表:
list3 = [[14000, 13000], [22000], [12000, 13000], [24000], [12000, 14000], []]
实现代码
简洁写法(嵌套列表推导式)
直接通过两层列表推导式遍历嵌套结构完成映射,代码最精简:
list1 = [[2, 4], [3], [0, 4], [1], [0, 2], []] list2 = [12000,24000,14000,22000,13000,30000] list3 = [[list2[idx] for idx in sub_list] for sub_list in list1] # 验证输出 print(list3)
常规循环写法
逻辑更清晰,适合新手理解执行过程:
list1 = [[2, 4], [3], [0, 4], [1], [0, 2], []] list2 = [12000,24000,14000,22000,13000,30000] list3 = [] for sub_list in list1: current_sub = [] for index in sub_list: current_sub.append(list2[index]) list3.append(current_sub) # 验证输出 print(list3)
注意事项
该实现默认
list1中存储的索引值均在list2的下标合法范围内,如果存在非法索引,需要提前添加判断逻辑避免下标越界报错。
内容的提问来源于stack exchange,提问作者Barry Melon
相关产品推荐
相关产品推荐

