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

如何在二维NumPy数组中查找值并获取对应配对值?

二维数组查找指定值并获取配对值的简洁方案

问题场景

需要在二维数组(示例为[[11,'a'],[12,'b'],[13,'c'],[14,'d']])中查找指定值(如'd'),并获取其对应的配对值(如14)。尝试用np.where实现但未找到简洁方式,写出了冗余代码,现寻求更优解。

原冗余代码:

import numpy as np

ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
arr = np.array(ar)
x = np.where(arr == 'd')

print(x) 


print("x[0]:"+str(x[0])) 

print("x[1]:"+str(x[1])) 


a = str(x[0]).replace("[", "")
a = a.replace("]", "")
a = int (a)
print(a)

b = str(x[1]).replace("[", "")
b = b.replace("]", "")
b = int (b) -1
print(b)

print(ar[a][b]) 
#got 14

简洁解决方案

1. 正确使用numpy实现

np.where返回的是索引数组,直接通过索引取值即可,无需转字符串处理:

import numpy as np

ar = [[11,'a'],[12,'b'],[13,'c'],[14,'d']]
arr = np.array(ar)

# 获取目标值的行、列索引
row_idx, col_idx = np.where(arr == 'd')
# 取同一行的前一列作为配对值
result = arr[row_idx[0], col_idx[0] - 1]
print(result)  # 输出14

如果存在多个匹配值,可遍历row_idx和col_idx逐个处理。

2. 无需numpy的轻量实现

如果原数据是普通列表,直接遍历即可,代码更简洁:

ar = [[11,'a'],[12,'b'],[13,'c'],[14,'d']]
target = 'd'

# 找到包含目标值的行,取第一个元素作为配对值
result = next(row[0] for row in ar if row[1] == target)
print(result)  # 输出14

若目标值可能不存在,可添加默认值避免报错:

result = next((row[0] for row in ar if row[1] == target), None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:35:20