【问题标题】:Keep getting TypeError: 'list' object is not callable不断收到 TypeError: 'list' object is not callable
【发布时间】:2019-02-23 16:42:39
【问题描述】:

我不确定我的错误在哪里,但这是我从index = plottest(doc) 收到错误的代码:

for doc in plottest:

    for word in wordsunique:

        if word in doc:
            word = str(word)
            index = plottest(doc)
            positions = list(np.where(np.array(index) == word)[0])
            idfs = tfidf(word,doc,plottest)

            try:
                worddic[word].append([index, positions, idfs])
            except:
                worddic[word] = []
                worddic[word].append([index, positions, idfs])

【问题讨论】:

  • 大概plottest 是一个列表,而您似乎认为它是一个函数。不能说更多,因为您没有告诉我们plottest 的定义或分配位置。

标签: python list compiler-errors python-3.6


【解决方案1】:

正如@Robin Zigmond 在评论中所说,您正尝试使用(...) 语法调用 列表,就像调用函数一样。以下:

>>> def f(x): return 2*x
... 
>>> f(2)
4

不同于:

>>> L=[1,2,3]
>>> L(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

后者不起作用,因为[1,2,3] 不可调用。 The Python documentation 枚举可调用类型:

  • 用户自定义函数
  • 实例方法
  • 生成器函数
  • 协程函数
  • 异步生成器函数
  • 内置函数
  • 内置方法
  • 类实例:可以通过在类中定义__call__() 方法来调用任意类的实例。

列表(即list 实例)都不是,因为list 类没有__call__() method

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

在您的示例中,第一行声明 plottest 是可迭代的。错误显示它是一个列表。您尝试使用index = plottest(doc) 调用它。我的猜测是你想在plottest 中获取doc 的索引。要在 Python 中实现这一点,您可以编写:

for index, doc in enumerate(plottest):
    ...

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2022-11-20
    • 2015-05-26
    • 2016-01-09
    • 1970-01-01
    • 2020-08-08
    • 2018-03-31
    相关资源
    最近更新 更多