什么是TypeError: 'NoneType'对象是不可迭代的意思?例子:

for row in data:  # Gives TypeError!
    print(row)

当前回答

另一种可能产生这种错误的情况是,当你设置某个值等于函数的返回值时,却忘记实际返回任何值。

例子:

def foo(dict_of_dicts):
    for key, row in dict_of_dicts.items():
        for key, inner_row in row.items():
            Do SomeThing
    #Whoops, forgot to return all my stuff

return1, return2, return3 = foo(dict_of_dicts)

这是一个很难发现的错误,因为如果行变量恰好在某个迭代中为None,也会产生错误。发现它的方法是跟踪在最后一行失败,而不是在函数内部。

如果你只从一个函数返回一个变量,我不确定是否会产生错误…我怀疑错误"'NoneType'对象在Python中不可迭代"在这种情况下实际上是在暗示"嘿,我试图遍历返回值并将它们按顺序分配给这三个变量但我只得到None来迭代"

其他回答

这意味着数据变量传递的是None(类型为NoneType),它的等效值为空。所以它不能像你尝试的那样,作为一个列表是可迭代的。

我在数据库里对熊猫犯了这个错误。

此错误的解决方案是在集群中安装库 在这里输入图像描述

它意味着data为None,这不是一个可迭代对象。添加or[]*可以防止异常并且不打印任何东西:

for row in data or []:  # no more TypeError!
    print(row)

*归功于先前的一些评论;请注意,引发异常也可能是一种预期的行为和/或数据设置不当的指示。

错误解释:“NoneType”对象不可迭代

在python2中,NoneType是None的类型。在Python3中,NoneType是None类,例如:

>>> print(type(None))     #Python2
<type 'NoneType'>         #In Python2 the type of None is the 'NoneType' type.

>>> print(type(None))     #Python3
<class 'NoneType'>        #In Python3, the type of None is the 'NoneType' class.

遍历值为None的变量失败:

for a in None:
    print("k")     #TypeError: 'NoneType' object is not iterable

如果Python方法没有返回值,则返回NoneType:

def foo():
    print("k")
a, b = foo()      #TypeError: 'NoneType' object is not iterable

你需要检查你的循环结构的NoneType像这样:

a = None 
print(a is None)              #prints True
print(a is not None)          #prints False
print(a == None)              #prints True
print(a != None)              #prints False
print(isinstance(a, object))  #prints True
print(isinstance(a, str))     #prints False

Guido说,只使用is检查None,因为它对身份检查更健壮。不要使用相等操作,因为这些操作本身就会产生泡沫。Python的编码风格指南- PEP-008

NoneTypes是鬼鬼祟祟的,可以从lambdas潜入:

import sys
b = lambda x : sys.stdout.write("k") 
for a in b(10): 
    pass            #TypeError: 'NoneType' object is not iterable 

NoneType不是一个有效的关键字:

a = NoneType     #NameError: name 'NoneType' is not defined

None和字符串的连接:

bar = "something"
foo = None
print foo + bar    #TypeError: cannot concatenate 'str' and 'NoneType' objects

这是怎么回事?

Python的解释器将你的代码转换为pyc字节码。Python虚拟机处理字节码时,遇到了一个循环构造,该构造说迭代一个包含None的变量。该操作是通过调用None.对象上的__iter__方法来执行的。

None没有定义__iter__方法,所以Python的虚拟机会告诉你它看到了什么:NoneType没有__iter__方法。

这就是为什么Python的鸭子类型思想被认为是不好的。程序员对一个变量做了一些完全合理的事情,但在运行时它被None污染了,python虚拟机试图继续前进,并把一堆无关的废话吐得满地都是。

Java或c++没有这些问题,因为这样的程序不允许编译,因为您还没有定义发生None时该做什么。Python允许你做很多在特殊情况下不应该被期望工作的事情,这给了程序员很多自缢的绳子。Python是一个应声虫,当它想要阻止你伤害自己时,它会说“是”,就像Java和c++一样。

这意味着data的值为None。