简体   繁体   English

查找列表中最后一次出现唯一值的索引

[英]Find index of last occurrence of unique value in a list

Consider the list a = [1,2,3,5,6,1,2,4,5]考虑列表a = [1,2,3,5,6,1,2,4,5]

output is the index of last occurrence of unique value.输出是最后一次出现唯一值的索引。 idx = [5,6,2,7,8,4]

I have actually tried this out我实际上已经尝试过了

if len(a) != 0:
    #just keep unique ind_prof(col5) (last occurance=default)
    unique_val = np.unique(a)
    idx = [(len(a) - 1 - a[::-1].index(i)) for i in unique_val]

This seems to be working but just wanted to know if there's a better way to do this这似乎有效,但只是想知道是否有更好的方法来做到这一点

Because you wany index of last occurrence you can reverse list and find index and minus this index from len(a) and find you want like below:因为你last occurrence index很差,你可以reverse列出并找到索引并从len(a) minus这个索引,然后找到你想要的,如下所示:

a = [1,2,3,5,6,1,2,4,5]
b = a[::-1]
print(b)

[(len(a) - b.index(i) -1) for i in set(a)] 

Output:输出:

# b
[5, 4, 2, 1, 6, 5, 3, 2, 1]
# last occurrence index
[5, 6, 2, 7, 8, 4]

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

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