【问题标题】:Inconsistent type of *args*args 的类型不一致
【发布时间】:2015-01-26 13:20:40
【问题描述】:

我正在尝试在 python 2.7 中编写一个通用的记忆函数(在 3.x 中没有问题)

def init_memoize():
    fns = dict()
    def memoize(fn, *args):
        if fn not in fns:
            fns[fn] = dict()
        print type(args)       # prints "<type 'tuple'>"
        print args in fns[fn]  # throws the error
        if args not in fns[fn]:
            fns[fn][args] = fn(*args)
        return fns[fn][args]
    return memoize
memoize = init_memoize()

memoize(sorted, range(5))
memoize(sorted, range(10))

当我尝试运行此代码时,我在指出的行中收到错误 TypeError: unhashable type: 'list',但在此之前,我验证了 args 的类型是一个可散列的元组。

有人能解释一下为什么args 的类型会发生变化吗?

【问题讨论】:

  • 您没有在实际调用memoize 的位置显示任何代码。你传递的参数是什么?

标签: python python-2.7 hash arguments memoization


【解决方案1】:

其中包含列表的元组仍然不可散列,原因与列表不可散列相同。

>>> args = ([],)
>>> type(args)
<type 'tuple'>
>>> d = {args: None}
TypeError: unhashable type: 'list'
>>> hash(args)
TypeError: unhashable type: 'list'

【讨论】:

  • 谢谢,我忘了 range 在 2.7 中返回一个列表
猜你喜欢
  • 2018-01-12
  • 2015-09-25
  • 2021-07-04
  • 2016-02-03
  • 2013-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多