arrays - Swift - 基于另一个称为查询的数组有效地查询一个整数数组,该数组具有第一个数组的索引
问题描述
我想根据另一个称为查询的数组有效地查询一个整数数组,该数组具有第一个数组的索引。
let arrayWithData = [10, 20, 30, 15, 25, 35, 56]
let queries = [2, 4, 6]
新数组应返回:
let queriedArray = [30, 25, 56]
解释:
30 是 arrayWithData 的索引 2
25 是 arrayWithData 的索引 4
56 是 arrayWithData 的索引 6
如何在不使用循环的情况下快速有效地实现这一点。也许使用地图或过滤器
解决方案
你可以试试
let res = queries.compactMap { $0 < arrayWithData.count ? arrayWithData[$0] : nil }
如果您 100% 确定查询索引将在数组计数中使用
let res = queries.map{ arrayWithData[$0]}
推荐阅读
- string - 不能在 MIPS 中多次写入文件?
- javascript - 将字典输出到表:关键顺序问题
- vba - 尝试从现有 Word 邮件合并文档中提取邮寄地址
- python - 如何使用单词列表计算数据框中的字数?
- reactjs - 在 react 中直接使用 QuillJS 而不使用 react-quill
- algorithm - 这个输出会是什么?
- algorithm - 如何使用 Google OR 工具解决流游戏?
- android - 是否有任何颤振包可以从当前位置数据中获取最近地点的列表
- c++ - 我试图了解形式参数如何在 C++ 中工作
- azure - 我们能否通过 ARM Tempalate 为 Azure 数据工厂启用 CMK 客户管理的密钥加密?