【问题标题】:Storing tuple from generator in dictionary in Python在 Python 中将生成器中的元组存储在字典中
【发布时间】: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


【解决方案1】:

确实,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)

【讨论】:

  • 这是个好建议。谢谢。限时结束我会尽快接受!
猜你喜欢
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 2017-07-16
  • 1970-01-01
  • 2021-12-24
  • 2016-02-13
  • 2011-02-22
  • 2013-05-06
相关资源
最近更新 更多