[英]Python - Alternative for using numpy array as key in dictionary
I'm pretty new to Python numpy. 我是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. 我试图在我的一个函数中使用numpy数组作为字典中的键,然后Python解释器告诉我numpy数组不可哈希。 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. 我刚刚发现,解决此问题的一种方法是使用repr()
函数将numpy数组转换为字符串,但看起来非常昂贵。 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. 更新:我可以创建一个新类来包含numpy数组,这似乎是实现我想要的正确方法。 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. 更新2:使用一个类在数组中包含数据,然后重写__hash__
函数是可以接受的,但是,我希望使用@hpaulj提供的解决方案。 Convert the array/list
to a tuple
fits my need in a better way as it does not require an additional class. 将array/list
转换为tuple
可以更好地满足我的需求,因为它不需要其他类。
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. 我想我已经知道了我自己问题的答案,所以我只把它们写下来。
array
and then override __hash__
function to amend the way how it is hashed as mentioned by ZdaR 写一个类以包含在数据array
,然后覆盖__hash__
函数修改它是如何通过提及散列方式ZdaR array
to a tuple
, which makes the list hashable instantaneously.Thanks to hpaulj 这个转换array
的tuple
,这使得该列表可哈希 instantaneously.Thanks到hpaulj I'd prefer method No.2 because it fits my need better, as well as simpler. 我更喜欢No.2方法,因为它更适合我,也更简单。 However, using a class might bring some additional benefits so it could also be useful. 但是,使用类可能会带来一些其他好处,因此它也很有用。
If you want to quickly store a numpy.ndarray
as a key in a dictionary, a fast option is to use ndarray.tobytes () which will return a raw python bytes
string which is immutable 如果您想快速将numpy.ndarray
作为键存储在字典中,则快速的选择是使用ndarray.tobytes (),它将返回一个不可变的原始python bytes
字符串
my_array = numpy.arange(4).reshape((2,2))
my_dict = {}
my_dict[my_array.tobytes()] = None
I just ran into that issue and there's a very simple solution to it using list comprehension: 我只是遇到了这个问题,使用列表理解有一个非常简单的解决方案:
import numpy as np
dict = {'key1':1, 'key2':2}
my_array = np.array(['key1', 'key2'])
result = np.array( [dict[element] for element in my_array] )
print(result)
The result should be: 结果应为:
[1 2]
I don't know how efficient this is but seems like a very practical and straight-forward solution, no conversions or new classes needed :) 我不知道这有多有效,但似乎是一个非常实用且直接的解决方案,不需要任何转换或新的类:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.