[英]python: replace list items with index of items in another list
我有2个清单,例如说
list1 = ['abc', 'xyz', 'cat', 'xyz', 'abc', 'pqr', 'dog']
list2 = ['xyz', 'dog', 'pqr', 'abc', 'cat']
我想通过将list1
替换为list2
元素的索引来创建新列表,例如
list3 = [3, 0, 4, 0, 3, 2, 1]
我应该在这里提一下,我实际上是通过以下方式从list1
获取list2
的:
list2 = list(set(list1))
因此, list2
没有重复项,并且具有list1
所有元素。
我想知道以list3
方式获取list3
的最快方法。 到目前为止,我已经尝试了两种方法:
1>基本的.index
方式
list3 = [list2.index(item) for item in list1]
2>使用以元素作为键和索引作为值的字典
d = {list2[i]:i for i in range(len(list2))}
list3 = [d[item] for item in list1]
如果您担心要查找重复值,只需先创建一个索引:
>>> idx={e:list2.index(e) for e in list2}
或者:
>>> idx={e:n for n,e in enumerate(list2)}
然后:
>>> [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.