【问题标题】:How to get the items of an array based on the indexes stored in another array如何根据存储在另一个数组中的索引获取数组的项
【发布时间】:2021-01-20 13:13:42
【问题描述】:

我有两个数组:

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

a 包含所有项目,b 包含我感兴趣的项目的索引。
所以我想创建一个函数来提取数组b中指定的索引处的项目。

我可以用 for 循环来做:

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

为了清楚起见,所需的输出是:

香蕉橙猕猴桃

问题在于,如果数字很大,for 循环会太慢。
我想知道是否存在复杂度较低的东西。

【问题讨论】:

  • 反过来,只迭代索引,避免 if 测试:for anIndex in b { print(a[index]) }
  • @Larme 这真的很聪明,谢谢!
  • if i == b[i] 表示 if b.contains(i),这将在 b 上迭代每个?如果你想“提取”所说的值(不仅仅是打印),在高级方法中:let extracted = b.map { a[$0] }

标签: ios arrays swift


【解决方案1】:

您可以简单地映射索引并返回相关元素:


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"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 2016-05-26
    • 1970-01-01
    • 2018-03-28
    • 2017-03-17
    • 1970-01-01
    • 2021-08-06
    • 2021-06-24
    相关资源
    最近更新 更多