You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取两数组匹配元素的索引并提取目标数组对应元素?

解决方案(Swift)

步骤1:获取list2中与list1匹配元素的索引

你可以用enumerated()遍历list2,它会返回每个元素的索引(offset)和元素值(element),再筛选出存在于list1中的元素,最后提取索引即可:

let list1 = ["a", "c", "d", "f", "w"]
let list2 = ["a", "b", "c", "d", "e"]

// 获取匹配元素在list2中的索引
let matchingIndices = list2.enumerated()
    .filter { list1.contains($0.element) }
    .map { $0.offset }
// 输出:[0, 2, 3]

步骤2:用索引从list3提取对应元素

拿到索引后,直接通过索引访问list3即可,建议加个索引越界判断避免崩溃:

let list3 = ["v", "w", "x", "y", "z"]

// 提取对应元素
let result = matchingIndices
    .filter { $0 < list3.count } // 确保索引在list3范围内
    .map { list3[$0] }
// 输出:["v", "x", "y"]

关于你之前的错误

list1.indices(of: list2)是错误的写法:Swift标准库的数组没有indices(of:)方法接收另一个数组作为参数,而且逻辑上你需要检查的是list2的元素是否在list1中,而非反过来。enumerated()正是解决这类“需要同时获取元素和索引”场景的最优选择。

内容的提问来源于stack exchange,提问作者ECN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:32:36