使用另一个列表中的值和另一个列表中的元素位置创建列表

时间:2014-05-14 02:34:56

标签: python list-comprehension

我有两个列表,list1list2; list1包含一些数据值,list2包含"元素位置"我想要存储list1的值。

我想创建另一个列表list3(包含len(list3) > len(list1)len(list3) > len(list1)),其中将list1的值放在list2中列出的位置}。

例如:

list1 = [3, 5, 11]
list2 = [2, 6, 8]

我想获得list3 = [ , , 3, , , 5, , , 11, ,]

最好的方法是获得空位"而不是零,但我不确定它是否可能。

我知道它可能会通过使用列表理解来解决,但我正在努力,因为有点而且无法弄明白。

1 个答案:

答案 0 :(得分:0)

首先,使用None表示"空值"。所以你的目标是获得:

list1 = [3, 5, 11]
list2 = [2, 6, 8]
list3 = [None, None, 3, None, None, None, 5, None, 11]

所以你应该使用None值初始化list3,索引等于list2包含的最大值,然后解析list2并将list1值插入list3:

list3 = [None for x in range(max(list2)+1)]
for x in range(len(list2)):
    try:
        list3[list2[x]] = list1[x]
    except IndexError: # list1 may not have the same number of elements than list2.
        pass

最后,你有:

>>> list3
[None, None, 3, None, None, None, 5, None, 11]

即使list1不包含与list2相同数量的元素,即使list2中的元素未排序,此解决方案仍然有效。