Python - 使用numpy数组作为字典中的关键字的替代方法 [英] Python - Alternative for using numpy array as key in dictionary
问题描述
repr()
函数将numpy数组转换为字符串,但是似乎非常昂贵。有没有更好的方式来实现同样的效果? 更新:我可以创建一个新类来包含numpy数组,这似乎是正确的方式来实现我想要的。只是想知道是否有更好的方法?
更新2:使用类包含数组中的数据,然后覆盖 __ hash __
函数是可以接受的,但是我更喜欢@hpaulj提供的解决方案。将数组/列表
转换为元组
可以更好地满足我的需要,因为它不需要额外的类。
完成了一些研究并阅读了所有评论。我想我已经知道自己的问题的答案,所以我只是写下来。
我更喜欢方法2,因为它更适合我的需要,以及更简单。但是,使用课程可能会带来一些额外的好处,因此也可能会有用。
I'm pretty new to Python numpy. I was attempted to use numpy array as the key in dictionary in one of my functions and then been told by Python interpreter that numpy array is not hashable. I've just found out that one way to work this issue around is to use repr()
function to convert numpy array to a string but it seems very expensive. Is there any better way to achieve same effect?
Update: I could create a new class to contain the numpy array, which seems to be right way to achieve what I want. Just wondering if there is any better method?
update 2: Using a class to contain data in the array and then override __hash__
function is acceptable, however, I'd prefer the solution provided by @hpaulj. Convert the array/list
to a tuple
fits my need in a better way as it does not require an additional class.
After done some researches and reading through all comments. I think I've known the answer to my own question so I'd just write them down.
- Write a class to contain the data in the
array
and then override__hash__
function to amend the way how it is hashed as mentioned by ZdaR - Convert this
array
to atuple
, which makes the list hashable instantaneously.Thanks to hpaulj
I'd prefer method No.2 because it fits my need better, as well as simpler. However, using a class might bring some additional benefits so it could also be useful.
这篇关于Python - 使用numpy数组作为字典中的关键字的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!