python - 在Python中将生成器中的元组存储在字典中

标签 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 异常,因为我猜测 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/

相关文章:

python - R 与 scikit-learn 中线性回归 R2 的交叉验证

python : The most efficient way to join two very big (20+ GB) datasets?

c# - 如何通过换行字典<string,string>将字符串拆分为键值对

python - 根据条件在 Pandas 数据框中创建列

javascript - 在 typescript 中遍历可变元组

python - 在python中使用opencv在图像的高斯模糊期间出现错误。代码之前运行正常,并且突然出现错误

python - 如何将 '-'字符串解析到node js本地脚本?

python - 将 Tensorflow 模型转换为 tensorflow-lite (.tflite) 格式时出现问题

Python 文本文件到字典中不起作用

syntax - scala 将多个函数调用参数合并到一个元组中——可以禁用它吗?