【问题标题】:Map elements of a list to their index in another list将列表的元素映射到另一个列表中的索引
【发布时间】:2019-05-17 00:23:59
【问题描述】:

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

list1list2 的超集。

对于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 = ['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 []

请提出前进的方向。

【问题讨论】:

  • 我重新打开了这个问题,因为来自标记副本的接受答案为 OP 的第二个示例产生了错误的结果。骗子产生[0, 1],但OP想要[1, 0]
  • 换句话说,OP 想要将list1 的元素映射到它们在list2 中的索引。
  • list2 = ['c','a'] 的预期结果是什么?

标签: python list indexing


【解决方案1】:

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

>>> list1 = ['a','b','c','d']                                                                                            
>>> list2 = ['d','a', 'f']
>>> print([list2.index(x) for x in list1 if x in list2])

【讨论】:

  • 虽然正确,但请注意,它的时间复杂度为 O(len(list1)*len(list2))。
【解决方案2】:

由于list2list1 的子集,您可以构造字典映射,然后对list2 的值使用dict.__getitem__ 来提取索引:

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]

【讨论】:

  • @timgeb,是的,但d.get 在功能上并不等同。由于__getitem__ 保证如果list2 值不在list1 中,您将收到错误。
  • 可以:d = dict(enumerate(list1)),我觉得更好
  • @Aaron_ab 不,创建索引:值映射,我们需要值:索引。
  • @Aaron_ab,你需要dict(map(reversed, enumerate(list1)))。但我发现理解更具可读性。
【解决方案3】:

我建议使用字典将 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多