繁体   English   中英

不断收到TypeError:“列表”对象不可调用

[英]Keep getting TypeError: 'list' object is not callable

我不确定我的错误在哪里,但是这是我从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])

正如@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]是不可调用的。 Python文档列举了可调用的类型:

  • 用户定义的功能
  • 实例方法
  • 发电机功能
  • 协程功能
  • 异步发电机功能
  • 内建功能
  • 内置方法
  • 类实例: 通过在类中定义__call__()方法,可以使任意类的实例成为可调用的。

列表(即list实例)都不是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):
    ...

希望能帮助到你!

暂无
暂无

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

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