将列表转换为不同的列表并映射索引

问题描述 投票:2回答:2

我有一个对象列表,我想将所有索引映射到新索引时将其转换为一个不同的列表。

例:

列表:["a", "b", "a", "d"] - > ["a", "b", "d"]

地图:

{
  0: 0, //0th index of original list is now 0th index of distinct list
  1: 1,
  2: 0, //2nd index of original list is now 0th index of distinct list
  3: 2  //3rd index of original list is now 2th index of distinct list
} 

是否有一种简单的方法可以使用单线程或在kotlin中使用相当简单的解决方案来完成此操作?

kotlin distinct-values
2个回答
4
投票

以下表达式将执行此操作:

val p = listOf("a", "b", "a", "d").let {
  val set = it.distinct().mapIndexed { i, v -> v to i }.toMap()
  it.mapIndexed { i, v -> i to set.getValue(v) }
}.toMap()

1
投票

我认为这可以很好地解决问题:

val orig = listOf("a", "b", "a", "c")

val positions = orig.distinct().let { uniques ->
    orig.withIndex().associate { (idx, e) -> idx to uniques.indexOf(e) }
}
© www.soinside.com 2019 - 2024. All rights reserved.