在元组数组中查找元组并返回所搜索元组的索引

2024-04-24 04:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,里面的坐标是元组的数组

import numpy as np

data = np.arange(0, 18)
coord = [(i, i, i) for i in data]
arr = np.empty(18, dtype=object)
arr[:] = coord
arr = arr.reshape(3, 6)

d = dict()
d.update({'coord': arr}) 

我想用一个坐标查询字典,然后返回它在数组中的索引。你知道吗

当我试图用np.where查找索引时,它不返回匹配。你知道吗

np.where(d['coord'] == (0, 0, 0))
(array([], dtype=int64),)

这将理想地返回索引(0, 0)。你知道吗

当为字典条目和元组值提供索引时,它返回True,因此元组存在于索引中。你知道吗

d['coord'][0,0] == (0, 0, 0)
True

我可以这样得到索引吗??你知道吗

谢谢。你知道吗


Tags: importnumpytruefordata字典asnp
1条回答
网友
1楼 · 发布于 2024-04-24 04:33:25

问题在于对具有元组的对象数组的==测试。你知道吗

In [346]: d['coord']                                                            
Out[346]: 
array([[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)],
       [(6, 6, 6), (7, 7, 7), (8, 8, 8), (9, 9, 9), (10, 10, 10),
        (11, 11, 11)],
       [(12, 12, 12), (13, 13, 13), (14, 14, 14), (15, 15, 15),
        (16, 16, 16), (17, 17, 17)]], dtype=object)
In [347]: d['coord']==(0, 0, 0)                                                 
/usr/local/bin/ipython3:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
  #!/usr/bin/python3
Out[347]: False

解决方案是将一个对象数组与另一个对象数组进行比较:

In [348]: x=np.array(None); x[()]=(0,0,0)                                       
In [349]: x                                                                     
Out[349]: array((0, 0, 0), dtype=object)
In [350]: d['coord']==x                                                         
Out[350]: 
array([[ True, False, False, False, False, False],
       [False, False, False, False, False, False],
       [False, False, False, False, False, False]])

相关问题 更多 >