Python 从其他列表中查找职位并在其他列表中应用该职位

Python 从其他列表中查找职位并在其他列表中应用该职位,python,list,Python,List,例如,我有3个列表 list1 = [30,14,42,17,18] list2 = [17,18,6,7,30,9,5,14,3,42,33] list3 = [[-25,54,789,0.56],[-5,4,9,0.5],[-5,4,0.009,0.8],[-5,456,7,56], [-5,4,9,0.6],[-2,4,9,-0.578],[-2,0.5,-7,-0.6],[-25,-50,78,0.1],[-4,-58,79,0.6], [-2,5,7,4],[-5,54,43,0.

例如,我有3个列表

list1 = [30,14,42,17,18]

list2 = [17,18,6,7,30,9,5,14,3,42,33]

list3 = [[-25,54,789,0.56],[-5,4,9,0.5],[-5,4,0.009,0.8],[-5,456,7,56],
[-5,4,9,0.6],[-2,4,9,-0.578],[-2,0.5,-7,-0.6],[-25,-50,78,0.1],[-4,-58,79,0.6],
[-2,5,7,4],[-5,54,43,0.45]]
列表2和列表3的长度相同


我的问题是取
list1
中的每个值,在
list2
中找到它的位置,从同一位置从
list3
中提取值。这些列表是在运行时生成的,即ID和值在运行时会发生变化。

您可以使用dict理解和
枚举
dict2
创建一个数字到索引的映射,然后使用映射将
list1
中的数字映射到映射索引处
list3
中相应的子列表:

mapping = {n: i for i, n in enumerate(list2)}
print([list3[mapping[n]] for n in list1])
这将产生:

[[-5, 4, 9, 0.6], [-25, -50, 78, 0.1], [-2, 5, 7, 4], [-25, 54, 789, 0.56], [-5, 4, 9, 0.5]]

请注意,首先创建映射将问题的平均时间复杂度降低到O(n)。

您可以使用dict理解和
枚举
dict2
创建一个数字到索引映射,然后使用映射将
list1
中的数字映射到映射索引处
list3
中相应的子列表:

mapping = {n: i for i, n in enumerate(list2)}
print([list3[mapping[n]] for n in list1])
这将产生:

[[-5, 4, 9, 0.6], [-25, -50, 78, 0.1], [-2, 5, 7, 4], [-25, 54, 789, 0.56], [-5, 4, 9, 0.5]]

请注意,首先创建映射将问题的平均时间复杂度降低到O(n)。

使用列表理解

In [67]: print [list3[j] for j in [list2.index(i) for i in list1]]
Out[67]: 
[[-5, 4, 9, 0.6],
 [-25, -50, 78, 0.1],
 [-2, 5, 7, 4],
 [-25, 54, 789, 0.56],
 [-5, 4, 9, 0.5]]


使用列表理解

In [67]: print [list3[j] for j in [list2.index(i) for i in list1]]
Out[67]: 
[[-5, 4, 9, 0.6],
 [-25, -50, 78, 0.1],
 [-2, 5, 7, 4],
 [-25, 54, 789, 0.56],
 [-5, 4, 9, 0.5]]


你好你试图用什么方法来解决这个问题?嗨!您试图解决这个问题的方法是什么?
[list3[list2.index(i)]对于列表1中的i
仍然具有O(n^2)的平均时间复杂度,因为对于
list1
的每次迭代,需要O(n)使用
list.index
方法在
list2
中查找
i
[list3[list2.index(i)]对于列表1中的i]
仍然具有O(n^2)的平均时间复杂度,因为对于
list1
上的每次迭代,需要O(n)使用
list.index
方法在
list2
中查找
i