如何用Python将数组按指定索引数组拆分为两个子数组?
简洁高效的数组分组方案
嘿,这个需求我之前处理过,给你几个简洁又高效的方案,分情况选就行!
方案一:用Set优化查找(推荐,高效)
如果你的数组或者索引集合比较大,这个方法绝对是首选——把索引数组转成Set后,查找索引的时间复杂度是O(1),整个过程只需要遍历原数组一次,效率拉满:
const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const idx = [0, 3, 4, 6]; // 先把索引转成Set,提升查找速度 const idxSet = new Set(idx); const selected = []; const remaining = []; // 一次遍历完成分组 arr.forEach((item, index) => { idxSet.has(index) ? selected.push(item) : remaining.push(item); }); console.log(selected); // 输出 [1, 4, 5, 7] console.log(remaining); // 输出 [2, 3, 6, 8]
这个方案的时间复杂度是O(n)(n是原数组长度),空间复杂度只需要存储索引Set,非常高效。
方案二:函数式风格的reduce写法
如果偏爱函数式编程的紧凑写法,可以用reduce把遍历和分组一步完成,代码看起来更简洁:
const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const idx = [0, 3, 4, 6]; const idxSet = new Set(idx); // 用reduce直接生成包含两个子数组的对象 const { selected, remaining } = arr.reduce((acc, item, index) => { const targetKey = idxSet.has(index) ? 'selected' : 'remaining'; acc[targetKey].push(item); return acc; }, { selected: [], remaining: [] }); console.log(selected); // [1, 4, 5, 7] console.log(remaining); // [2, 3, 6, 8]
本质和方案一一样,只是写法更“函数式”,适合喜欢这种风格的场景。
方案三:直观的map+filter(适合小规模数据)
如果你的数组和索引集合都很小,这个写法最直观,虽然需要遍历原数组两次,但代码简单易懂:
const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const idx = [0, 3, 4, 6]; // 先获取选中的元素 const selected = idx.map(i => arr[i]); // 过滤掉选中索引的元素,得到剩余部分 const remaining = arr.filter((_, index) => !idx.includes(index)); console.log(selected); // [1, 4, 5, 7] console.log(remaining); // [2, 3, 6, 8]
注意:这个方案里idx.includes(index)的时间复杂度是O(k)(k是索引数组长度),所以整体是O(n*k),如果索引数组很大,效率会比前两种低,所以只推荐小规模数据用。
内容的提问来源于stack exchange,提问作者Vipasana
相关产品推荐
相关产品推荐

