【问题标题】:TypeError: 'function' object is not iterable' Python 3TypeError:'函数'对象不可迭代' Python 3
【发布时间】:2018-04-30 15:12:52
【问题描述】:

我正在尝试编写一个程序,该程序将从网络上打开一个包含 10,000 个单词的文本文件,然后“清理”该文件以删除无意义的单词,例如“aa”。我最终想用这些词做其他事情,所以我想将非“无意义”的词添加到新列表中。每次我尝试运行它时都会遇到错误代码TypeError: 'function' object is not iterable

import urllib.request  

def readWordList():  

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList() 

def clean(aList):   
    newList = []
    for word in aList: 
        if range(len(word)) >= 2:
            newList.append(word)
    return newList


clean(clean)

【问题讨论】:

  • 请修正缩进,并包含完整的回溯。
  • clean(clean)?函数和列表不能使用相同的名称..

标签: python python-3.x file error-handling


【解决方案1】:

下定决心:clean 应该是列表还是函数?您从一个列表开始,但随后将其替换为一个函数,然后告诉该函数自行清理。试试这个:

dirty_list = readWordList()
def clean(aList):
...

clean(dirty_list)

【讨论】:

    【解决方案2】:

    您创建一个名为clean 的变量,立即通过声明同名函数来覆盖名称,然后将函数clean 传递给它自己。

    要么改变函数名,要么改变上面同名的变量。

    【讨论】:

      【解决方案3】:

      首先您创建一个名为clean 的变量,然后创建一个名为clean 的函数,最后您尝试在变量中使用该函数,两者都称为clean。当你定义一个函数时,你“销毁”了这个变量。它们必须有不同的名称。

      使用这个:

      import urllib.request  
      
          def readWordList():  
      
          response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
          html = response.read()
          data = html.decode('utf-8').split()
      
          return data
      
          to_clean = readWordList() # Use a different name so it won't be replaced later by the function
              def clean(aList):   
              newList = []
              for word in aList: 
                  if range(len(word)) >= 2:
                      newList.append(word)
              return newList
          clean(to_clean)
      

      问题解决了;现在他们有了不同的名字。

      【讨论】:

      • 这对前面的答案有什么补充?大声疾呼你的改进。
      • @Prune,我想我做了一个更好的解释,所以他会更好地理解它。但如果你愿意...我可以删除它...
      • 不——我想确保您的改进对以后的用户来说是显而易见的。 SGITE(东方最慢的枪)在 SO 上通常很有用。
      猜你喜欢
      • 2018-06-21
      • 2015-09-29
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 2015-04-06
      • 2013-10-31
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多