簡體   English   中英

如何根據存儲在另一個數組中的索引獲取數組的項

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

我有兩個 arrays:

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

a包含所有項目, b包含我感興趣的項目的索引。
所以我想創建一個 function 來提取數組b中指定的索引處的項目。

我可以用 for 循環做 tis:

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

為了清楚起見,所需的 output 將是:

香蕉橙獼猴桃

問題是如果數字很大,for 循環會太慢。
我想知道是否存在復雜性較低的東西。

您可以簡單地 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"]

或擴展 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