kotlin - 将列表转换为不同的列表并映射索引
问题描述
我有一个对象列表,我想把它变成一个不同的列表,同时将所有索引映射到新索引。
例子:
列表:["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()
推荐阅读
- python - 有没有办法在另一列的列中找到每个值的出现次数?
- python - Python 多个日期时间合二为一
- c++ - 尝试在 iOS Xcode 项目中执行 C++ 给我一个错误
- javascript - Vue JS在悬停在某个图片上时显示一个块
- azure - 通过 ARM 模板为 Azure sql 数据库配置诊断设置
- google-sheets - 谷歌工作表从列中的一些值创建下拉列表
- python - 将多个字典值转换为单个输出
- node.js - 如何在 cloudinary nodejs 中添加文件夹 url
- ssl - 如何保护 JWT 令牌以避免将其从一台计算机共享到另一台计算机
- mongodb - 找到场景中副本最多的场景(必须指定剧名、幕名和场景名)