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

Numpy数组元素识别:按指定首索引提取元素生成新数组

嵌套数组元素提取方案

问题说明

给定嵌套数组:array = [[3,a],[3,b],[4,c],[7,d],[3,e]],需提取所有首元素等于指定值的子数组的第二个元素。例如指定值为3时,预期结果为[a,b,e]。

实现示例

JavaScript 实现

方法一:filter + map 组合

const array = [[3,'a'],[3,'b'],[4,'c'],[7,'d'],[3,'e']];
const target = 3;
// 先过滤出首元素匹配的子数组,再提取第二个元素
const result = array.filter(item => item[0] === target).map(item => item[1]);
console.log(result); // 输出 ['a','b','e']

方法二:reduce 一步完成

const array = [[3,'a'],[3,'b'],[4,'c'],[7,'d'],[3,'e']];
const target = 3;
// 遍历数组,符合条件的元素直接加入结果数组
const result = array.reduce((acc, curr) => {
  if (curr[0] === target) acc.push(curr[1]);
  return acc;
}, []);
console.log(result);

Python 实现

方法一:列表推导式(推荐)

array = [[3, 'a'], [3, 'b'], [4, 'c'], [7, 'd'], [3, 'e']]
target = 3
# 简洁的推导式,直接筛选并提取元素
result = [item[1] for item in array if item[0] == target]
print(result)  # 输出 ['a', 'b', 'e']

方法二:filter + map 组合

array = [[3, 'a'], [3, 'b'], [4, 'c'], [7, 'd'], [3, 'e']]
target = 3
# 先过滤匹配的子数组,再映射提取第二个元素
result = list(map(lambda x: x[1], filter(lambda x: x[0] == target, array)))
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:10:03