我有一个生成器函数,它计算 numpy 数组中的一些切片位置,如下所示:
import numpy as np
from itertools import product
def __get_slices(data_shape, start, offset, width, patch_size):
start_indices = [range(start[d] - offset if (start[d] - offset) >= 0 else 0,
start[d] - offset + width
if (start[d] - offset + width) <= data_shape[d]
else data_shape[d])
for d in range(len(data_shape))]
start_coords = product(*start_indices)
for start_coord in start_coords:
yield tuple(slice(coord, coord + patch_size) for coord in start_coord)
现在我想将这个生成的元组保存在一个字典中,该字典会抛出 TypeError
异常,因为我猜测 slice
对象是可变的
.有没有办法通过一些Python功能使其不可变并能够将其存储在字典中?
在 python2.7 上,尝试将其分配给字典时出现以下错误:
TypeError: unhashable type
最佳答案
事实上,slice()
对象是不可散列的,on purpose ,以确保 dict[slice] = Something
引发异常:
>>> d = {}
>>> d[42:81] = 'foobar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'slice'
您必须选择不同的对象,并稍后从这些对象创建切片。存储元组,例如:
yield tuple((coord, coord + patch_size) for coord in start_coord)
稍后当您需要应用它们时,使用 slice(*tup)
将它们转换为切片。
关于python - 在Python中将生成器中的元组存储在字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41615552/