Python 将列表中的元素映射到另一个列表中的索引

Python 将列表中的元素映射到另一个列表中的索引,python,list,indexing,Python,List,Indexing,我正在比较Python中的两个列表 list1是list2的超集 对于list1的元素,我希望它们的索引位于list2(如果存在) 这里有两个例子 list1 = ['a','b','c','d'] list2 = ['a','b'] 解决方案应产生[0,1] list1 = ['a','b','c','d'] list2 = ['b','a'] 解决方案应产生[1,0] list1 = ['a','b','c','d'] list2 = ['b','a'] pairwise = zip

我正在比较Python中的两个列表

list1
list2
的超集

对于
list1
的元素,我希望它们的索引位于
list2
(如果存在)

这里有两个例子

list1 = ['a','b','c','d']
list2 = ['a','b']
解决方案应产生
[0,1]

list1 = ['a','b','c','d']
list2 = ['b','a']
解决方案应产生
[1,0]

list1 = ['a','b','c','d']
list2 = ['b','a']

pairwise = zip (list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
print(matched_index) # prints []
我尝试了以下代码,但它只适用于第一个示例

list1 = ['a','b','c','d']
list2 = ['a','b']

pairwise = zip(list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
这很有效。但是,对于第二组示例数据,我得到了错误的输出
[]
,而不是预期的输出
[1,0]

list1 = ['a','b','c','d']
list2 = ['b','a']

pairwise = zip (list1,list2)
matched_index = [idx for idx, pair in enumerate(pairwise) if pair[0] == pair[1]]
print(matched_index) # prints []

请提出前进的方向。

我建议使用字典将
list2
中的元素映射到它们的索引-假设
list2
具有唯一的元素

>>> list1 = ['a','b','c','d']                                                                                            
>>> list2 = ['b','a']
>>> idx = {x:i for i,x in enumerate(list2)}                                                                            
>>> idx                                                                                                                
{'a': 1, 'b': 0}
现在你可以发布

>>> [idx[x] for x in list1 if x in idx]                                                                                
[1, 0]

由于
list2
list1
的一个子集,您可以构造一个字典映射,然后对
list2
的值使用
dict.\uu getitem\uuuu
来提取索引:

list1 = ['a','b','c','d']
list2 = ['a','b']
list3 = ['b','a']

d = {v: k for k, v in enumerate(list1)}

res1 = list(map(d.__getitem__, list2))  # [0, 1]
res2 = list(map(d.__getitem__, list3))  # [1, 0]

假设每个列表中都有唯一的元素,并且
len(list1)>=len(list2)


我重新打开这个问题是因为标记的重复项中的已接受答案为OP的第二个示例生成了错误的结果。dupe生成
[0,1]
,但OP想要
[1,0]
。换句话说,OP想要将
list1
的元素映射到
list2
中的索引。
list2=['c','a']
的预期结果是什么?虽然正确,但请注意这具有时间复杂度O(len(list1)*len len(list2))@timgeb,Yup,但是
d.get
在功能上是不等价的。由于
\uuu getitem\uuu
保证,如果
list2
值不在
list1
中,您将得到一个错误。可以执行:
d=dict(enumerate(list1))
,我找到了它nicer@Aaron_ab不,这会创建一个index:value映射,我们需要value:index。@Aaron_ab,您需要
dict(映射(反转,枚举(列表1))
。但我发现理解更具可读性。