如何通过搜索匹配值来打印2d数组的特定元素

时间:2018-12-12 08:29:21

标签: python arrays numpy

假设我有一个二维数组:

a = np.array[ ("words",3) , ("blah",7) , ("hmm",1 ]      

我有一个值:3.0

如何根据匹配值打印2d数组中的第一个索引?

所需的输出:words

这是我的代码:

k = np.array([["words words ", 4], ["blah blah", 1], [" please help me", 9]])
a = []
for i in range(len(k)):
    holder = (int(k[i,1]))
    a = np.append(a, holder)
    print(k[i,1])
    print(a, 'a')

a = np.asarray(a)
print('')
print( a )
print('')

close = (np.abs(a - dot)).argmin()  # dot is the value 0, it is the value of previous dot product computation
print(close , "close")
c = close
print(a[c])

1 个答案:

答案 0 :(得分:0)

如果您只想打印带有特定数字的字符串,则可以执行以下操作:

a = [("words",3), ("blah",7), ("hmm",1)]
b = [c[0] for c in a if c[1]==3]
print(b)
>>> b
['words']

如果您随后想要寻找一个与给定值尽可能接近的值,我会执行以下操作:

1。使用b中存在的所有数值构建一个数组a

2。创建一个元组数组,其中bdot中的值与其索引之间的绝对差为

3。在最后一个数组中查找最小值,并在b

中获取相应的索引

4。b[index]是要在a中查找的值。

def search_element(dot):
    b = [c[1] for c in a]
    index = min([(abs(f-dot),i) for i,f in enumerate(b)])[1]
    n = b[index]
    b = [c[0] for c in a if c[1]==n]
    return b
相关问题