我有一个对象列表,我想将所有索引映射到新索引时将其转换为一个不同的列表。
例:
列表:["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中使用相当简单的解决方案来完成此操作?
以下表达式将执行此操作:
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()
我认为这可以很好地解决问题:
val orig = listOf("a", "b", "a", "c")
val positions = orig.distinct().let { uniques ->
orig.withIndex().associate { (idx, e) -> idx to uniques.indexOf(e) }
}