【问题标题】:Find index of last occurrence of unique value in a list查找列表中最后一次出现唯一值的索引
【发布时间】:2021-09-08 13:32:19
【问题描述】:

考虑清单 a = [1,2,3,5,6,1,2,4,5]

输出是最后一次出现唯一值的索引。 idx = [5,6,2,7,8,4]

这个我已经试过了

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]

这似乎有效,但只是想知道是否有更好的方法来做到这一点

【问题讨论】:

  • 你尝试了什么?

标签: python python-3.x list set unique-index


【解决方案1】:

因为你在last occurrence 中缺少index,所以你可以从reverse 列出并找到索引和minus 这个索引从len(a) 并找到你想要的如下:

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)] 

输出:

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

【讨论】:

  • 集不维护秩序。
  • @Marichyasana 这不适用于答案,因为我在b 中有一个a 的临时值,并且我使用b 的索引,你说得对,但我不使用索引set 的我使用 b 的索引并且 b 没有改变
猜你喜欢
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
相关资源
最近更新 更多