在Python中使用字典中的生成器存储元组

时间:2017-01-12 14:22:39

标签: python dictionary tuples generator typeerror

我有一个生成器函数,它计算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异常的barf的字典中,因为我猜测slice对象是mutable。有没有办法通过一些python功能使其不可变,并能够将其存储在字典中?

在python2.7上,尝试将其分配给字典时出现以下错误:

TypeError: unhashable type

1 个答案:

答案 0 :(得分:2)

确实,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)时将其转换为片段。