【问题标题】:Python np where , variable as array index, tuplePython np where ,变量作为数组索引,元组
【发布时间】:2023-02-10 01:15:19
【问题描述】:

我想在二维数组中搜索一个值并获取对应的“对”的值 在此示例中,我想搜索“d”并获得“14”。 我确实尝试过 np location 但没有成功,我完成了这个垃圾代码,其他人有更聪明的解决方案吗?

`

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
`

【问题讨论】:

  • 你有什么理由不为此使用字典吗?
  • 为什么要为这些数据使用 numpy 数组?
  • 顺便说一句,不是转换为str然后做一堆字符串处理并返回int,你可以只做x[0][0]

标签: python variables indexing


【解决方案1】:

所以你想查找 key 并获得 value

感觉需要用dict

>>> ar=[[11,'a'],[12,'b'],[13,'c'],[14,'d']]
>>> d = dict([(k,v) for v,k in ar])
>>> d
{'a': 11, 'b': 12, 'c': 13, 'd': 14}
>>> d['d']
14

【讨论】:

    【解决方案2】:

    使用字典:

    dct = {k:v for v,k in ar}
    dct['d']
    

    【讨论】:

      猜你喜欢
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多