【发布时间】:2017-05-27 16:48:43
【问题描述】:
我有一个生成器函数,它计算 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 对象是mutable。有没有办法通过一些 python 功能使其不可变并能够将其存储在字典中?
在 python2.7 上,尝试将其分配给字典时出现以下错误:
TypeError: unhashable type
【问题讨论】:
-
啊,切片对象确实是不可散列的,故意的:Why are slice objects not hashable in python
-
@cxw:
TypeError: unhashable type: 'slice'将是错误。我当然可以重现。 -
@MartijnPieters 啊,这很有趣。我将尝试
reduce方法,如我们在该线程中所示;;/ -
@Luca:因为您在代码中只生成开始和停止值,所以只生成具有
(start, stop)值的元组会更简单。step值和slice.__reduce__返回的slice对象在这里也是多余的。
标签: python dictionary tuples generator typeerror