将列表变成不同的列表和地图索引
Turn a list into a distinct list and map indices
我有一个对象列表,我想将它变成一个不同的列表,同时将所有索引映射到新索引。
示例:
列表:["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) }
}
我有一个对象列表,我想将它变成一个不同的列表,同时将所有索引映射到新索引。
示例:
列表:["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) }
}