简体   繁体   English

python:用另一个列表中的项目索引替换列表项

[英]python: replace list items with index of items in another list

I have 2 lists, for example say 我有2个清单,例如说

list1 = ['abc', 'xyz', 'cat', 'xyz', 'abc', 'pqr', 'dog']
list2 = ['xyz', 'dog', 'pqr', 'abc', 'cat']

I want to create a new list by replacing list1 with indexes of the elements in list2 like 我想通过将list1替换为list2元素的索引来创建新列表,例如

list3 = [3, 0, 4, 0, 3, 2, 1]

I should mention here that I actually get list2 from list1 by 我应该在这里提一下,我实际上是通过以下方式从list1获取list2的:

list2 = list(set(list1))

So list2 has no duplicates and has all the elements of list1 . 因此, list2没有重复项,并且具有list1所有元素。

I want to know the fastest way I can get list3 in a pythonic way. 我想知道以list3方式获取list3的最快方法。 I have tried the 2 ways so far: 到目前为止,我已经尝试了两种方法:

1> basic .index way 1>基本的.index方式

list3 = [list2.index(item) for item in list1]

2> using a dict with elements as keys and indexes as values 2>使用以元素作为键和索引作为值的字典

d = {list2[i]:i for i in range(len(list2))}
list3 = [d[item] for item in list1]

If you have a concerned about looking up duplicate values, just create an index first: 如果您担心要查找重复值,只需先创建一个索引:

>>> idx={e:list2.index(e) for e in list2}

Alternatively: 或者:

>>> idx={e:n for n,e in enumerate(list2)}

Then: 然后:

>>> [idx[e] for e in list1]
[3, 0, 4, 0, 3, 2, 1]
idx = dict(zip(list2, range(len(list2))))
list(map(idx.get, list1))
# [3, 0, 4, 0, 3, 2, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM