python里numpy的替代用法_Python - 使用numpy数组作为字典中的关键字的替代方法

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 a tuple, 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值