簡體   English   中英

python:用另一個列表中的項目索引替換列表項

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM