python-3.x - How to efficiently create an indexed list in python?
问题描述
I have a list of strings, and another list of unique strings:
import numpy as np
source_list = ['cat', 'dog', 'dog', 'cat', 'cat', 'rat']
unique_list = ['cat', 'dog', 'rat'] # unique_list = np.unique(source_list)
How do I create the indexed_list
(which contains the indices of the unique_list
in the source_list
)
indexed_list = [0, 1, 1, 0, 0, 2]
I know the following implementation would work fine. But, is there an more efficient and pythonic way to create indexed_list
?
indexed_list = [None]*len(source_list)
for index, item in enumerate(source_list):
indexed_list[index] = np.where(unique_list == item)[0][0]
print(indexed_list)
解决方案
np.unique
与附加参数一起使用:
unique, index = np.unique(['cat', 'dog', 'dog', 'cat', 'cat', 'rat'], return_inverse=True)