繁体   English   中英

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

[英]Storing tuple from generator in dictionary in Python

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

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

TypeError: unhashable type

实际上, 故意确保slice()对象是不可散列的,以确保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)进行应用时将其slice(*tup)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM