TypeError: ‘NoneType’ 对象在 Python 中不可迭代
TypeError: ‘NoneType’ object is not iterable in Python
当我们尝试迭代一个None
值时,会出现 Python“TypeError: ‘NoneType’ object is not iterable”。要解决该错误,找出变量在何处被赋值None
并更正赋值或检查变量是否None
在迭代之前未存储。
下面是错误如何发生的示例。
my_list = None # ⛔️ TypeError: 'NoneType' object is not iterable for el in my_list: print(el)
我们正在尝试迭代一个None
值,但该值None
不可迭代,这会导致错误。
最常见的None
价值来源是:
- 有一个不返回任何东西的函数(
None
隐式返回)。 - 明确地将变量设置为
None
. - 将变量分配给调用不返回任何内容的内置函数的结果。
- 具有仅在满足特定条件时才返回值的函数。
不显式返回值的函数 return None
。
# 👇️ this function returns None def get_list(): print(['a', 'b', 'c']) # 👇️ None my_list = get_list() # ⛔️ TypeError: 'NoneType' object is not iterable for el in my_list: print(el)
您可以使用return
语句从函数返回值。
def get_list(): return ['a', 'b', 'c'] # 👈️ return value # 👇️ ['a', 'b', 'c'] my_list = get_list() for el in my_list: print(el) # 👉️ a, b, c
如果您需要在迭代之前if
检查变量是否未存储
值,请使用语句。None
my_list = None if my_list is not None: for i in my_list: print(i) else: # 👇️ this runs print('variable stores a None value')
或者,您可以提供一个空列表作为后备。
my_list = None for i in my_list or []: print(i)
sort()
)可以就地改变原始对象并返回None
。Make sure you aren’t storing the result of calling one in a variable.
Another common cause of the error is having a function that returns a value only
if a condition is met.
def get_list(a): if len(a) > 3: return a # 👇️ None my_list = get_list(['a', 'b']) # ⛔️ TypeError: 'NoneType' object is not iterable for i in my_list: print(i)
The if
statement in the get_list
function is only run if the passed in
argument has a length greater than 3
.
None
.To solve the error, you either have to check if the function didn’t return
None
, or return a default value if the condition is not met.
def get_list(a): if len(a) > 3: return a return [] # 👈️ return empty list if condition not met # 👇️ [] my_list = get_list(['a', 'b']) for i in my_list: print(i)
Now the function is guaranteed to return a value regardless if the condition is
met.
If you need to check if an object is iterable, use a try/except
statement.
my_str = 'hello' try: my_iterator = iter(my_str) for i in my_iterator: print(i) # 👉️ h, e, l, l, o except TypeError as te: print(te)
The iter() function
raises a TypeError
if the passed in value doesn’t support the __iter__()
method or the sequence protocol (the __getitem__()
method).
If we pass a non-iterable object like a None
value to the iter()
function,
the except
block is run.
my_list = None try: my_iterator = iter(my_list) for i in my_iterator: print(i) except TypeError as te: print(te) # 👉️ 'NoneType' object is not iterable
Examples of iterables include all sequence types (list
, str
, tuple
) and
some non-sequence types like dict
, file objects and other objects that define
an __iter__()
or a __getitem__()
method.
Conclusion #
当我们尝试迭代一个None
值时,会出现 Python“TypeError: ‘NoneType’ object is not iterable”。要解决该错误,找出变量在何处被赋值None
并更正赋值或检查变量是否None
在迭代之前未存储。