什么是TypeError: 'NoneType'对象是不可迭代的意思?例子:
for row in data: # Gives TypeError!
print(row)
什么是TypeError: 'NoneType'对象是不可迭代的意思?例子:
for row in data: # Gives TypeError!
print(row)
当前回答
这意味着数据变量传递的是None(类型为NoneType),它的等效值为空。所以它不能像你尝试的那样,作为一个列表是可迭代的。
其他回答
错误解释:“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++一样。
另一种可能产生这种错误的情况是,当你设置某个值等于函数的返回值时,却忘记实际返回任何值。
例子:
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来迭代"
因为使用for循环的结果只是一个值,而不是一组值
pola.py
@app.route("/search")
def search():
title='search'
search_name = request.form.get('search')
search_item = User.query.filter_by(id=search_name).first()
return render_template('search.html', title=title, search_item=search_item )
search.html(错误的)
{% for p in search %}
{{ p }}
search.html(正确)
<td>{{ search_item }}</td>
代码:用于数据中的行: TypeError: 'NoneType'对象不可迭代
它在抱怨哪个对象?二选一,行和数据。 在数据中的for行,需要是可迭代的?只有数据。
数据有什么问题?它的类型是NoneType。只有None类型为NoneType。所以data是None。
你可以在IDE中验证这一点,或者在for语句之前插入print "data is", repr(data),然后重新运行。
想想你接下来需要做什么: “无数据”应该如何表示?我们写一个空文件吗?我们是引发异常,还是记录警告,还是保持沉默?
当你得到None Exception时,继续循环,
例子:
a = None
if a is None:
continue
else:
print("do something")
这可以是来自DB或excel文件的任何可迭代对象。