简体   繁体   English

如何根据存储在另一个数组中的索引获取数组的项

[英]How to get the items of an array based on the indexes stored in another array

I have two arrays:我有两个 arrays:

let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]

a contains all the items and b contains the indexes of the ones I'm interested in. a包含所有项目, b包含我感兴趣的项目的索引。
So I would like to create a function to extract the items at the indexes specified in array b .所以我想创建一个 function 来提取数组b中指定的索引处的项目。

I can do tis with for loops:我可以用 for 循环做 tis:

for i in 0...a.count-1{
    if i == b[i]{
    print(a[i])
  }
}

To make it clear, the desired output would be:为了清楚起见,所需的 output 将是:

banana orange kiwi香蕉橙猕猴桃

The problem is that with big numbers the for loop would be too slow.问题是如果数字很大,for 循环会太慢。
I would like to know if there exists something with a lower complexity.我想知道是否存在复杂性较低的东西。

You can simply map the indices and return the associated elements:您可以简单地 map 索引并返回相关元素:


let aa = ["apple","banana","orange","pomelo","kiwi","melon"]
let bb = [1, 2, 4]

let elements = bb.map { aa[$0] }
print(elements)    // ["banana", "orange", "kiwi"]

Or extending RandomAccessCollection protocol:或扩展 RandomAccessCollection 协议:


extension RandomAccessCollection {
    func elements(at indices: [Index]) -> [Element] { indices.map { self[$0] } }
}

let a = ["apple","banana","orange","pomelo","kiwi","melon"]
let b = [1, 2, 4]

let elements = a.elements(at: b)    // ["banana", "orange", "kiwi"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM