什么是TypeError: 'NoneType'对象是不可迭代的意思?例子:
for row in data: # Gives TypeError!
print(row)
什么是TypeError: 'NoneType'对象是不可迭代的意思?例子:
for row in data: # Gives TypeError!
print(row)
当前回答
我在数据库里对熊猫犯了这个错误。
此错误的解决方案是在集群中安装库 在这里输入图像描述
其他回答
我在数据库里对熊猫犯了这个错误。
此错误的解决方案是在集群中安装库 在这里输入图像描述
因为使用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>
当你得到None Exception时,继续循环,
例子:
a = None
if a is None:
continue
else:
print("do something")
这可以是来自DB或excel文件的任何可迭代对象。
表示data的值为None。
错误解释:“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++一样。