首页 > 解决方案 > 在 Jupyter 笔记本上的 Python 中使用 sorted() 时出现“列表”对象不可调用错误

问题描述

我正在尝试下面的代码,我正在尝试读取文件的内容并识别 3 个最常用的单词。我将单个单词及其频率作为键:python dict中的值。当我尝试在其上使用 sorted() 时,出现“列表”对象不可调用错误。

content=open("Assignment1_Q8.txt").read().split()
freq={}
for item in content:
    if item in freq:
        freq[item]+=1
    else:
        freq[item]=1
    
print(freq)

freq_sort=sorted(freq,key=freq.values())

Output:
{'Hello': 5, 'World': 3, 'Hi': 3, 'Bye': 5}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-220-40658aa1ff31> in <module>
      8 print(freq)
      9 
---> 10 freq_sort=sorted(freq,key=freq.values())

TypeError: 'list' object is not callable

标签: pythonpython-3.xlistsortingjupyter-notebook

解决方案


问题是我之前使用了“排序”作为变量,后来我试图将它用作函数。我删除了“排序”变量并执行了代码,它可以工作。谢谢。


推荐阅读