Python - 使用numpy数组作为字典中的关键字的替代方法 [英] Python - Alternative for using numpy array as key in dictionary

查看:724
本文介绍了Python - 使用numpy数组作为字典中的关键字的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很熟悉Python numpy。我尝试在我的一个函数中使用numpy数组作为字典中的关键字,然后被Python解释器告知,numpy数组不可哈希。我刚刚发现,一种解决这个问题的方法是使用 repr()函数将numpy数组转换为字符串,但是似乎非常昂贵。有没有更好的方式来实现同样的效果?



更新:我可以创建一个新类来包含numpy数组,这似乎是正确的方式来实现我想要的。只是想知道是否有更好的方法?



更新2:使用类包含数组中的数据,然后覆盖 __ hash __ 函数是可以接受的,但是我更喜欢@hpaulj提供的解决方案。将数组/列表转换为元组可以更好地满足我的需要,因为它不需要额外的类。

解决方案

完成了一些研究并阅读了所有评论。我想我已经知道自己的问题的答案,所以我只是写下来。


  1. 编写一个类来包含数据在数组中,然后覆盖 __ hash __ 函数来修改如何将散列为 ZdaR 提到的

  2. 转换此数组 to a tuple ,这使得列表可哈希瞬间。感谢 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.

  1. 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
  2. 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.

这篇关于Python - 使用numpy数组作为字典中的关键字的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆