在 写Python代码的时候,“TypeError: 'XXX' object is not iterable” 是常见的错误之一。这个错误看似简单,却可能出现在多种场景中
“Iterable”(可迭代对象)指的是能够被 for 循环遍历的对象(如列表、元组、字符串、字典等),它们内部实现了 __iter__() 方法。
当我们试图对一个非可迭代对象使用 for 循环、解包(* 操作符)或其他需要可迭代特性的操作时,就会触发该错误。
for 循环# 错误:整数不是可迭代对象
num = 666
for i in num: # 试图遍历整数
print(i)报错:TypeError: 'int' object is not iterable
解决:确保 for 循环的对象是可迭代的(如将整数放入列表):
num = 123
for i in [num]: # 用列表包裹,使其可迭代
print(i) # 输出:123# 函数本应返回列表(可迭代),却返回了单个值
def get_data():
return 456
data = get_data()
for item in data:
print(item)报错:TypeError: 'int' object is not iterable
解决:修正函数返回值为可迭代对象:
def get_data():
return [456] # 返回列表(可迭代)
data = get_data()
for item in data:
print(item) # 输出:456*# 解包需要可迭代对象,而整数不可迭代
num = 789
print(*num) # 试图解包整数报错:TypeError: 'int' object is not iterable
解决:将非可迭代对象转为可迭代对象后再解包:
num = 789
print(*[num])# 字典的 values() 是可迭代的,但如果取值逻辑错误,可能返回单个非可迭代值
my_dict = {"a": 1, "b": 2}
value = my_dict.get("a") # 返回单个值 1(整数,非可迭代)
for v in value: # 错误:遍历单个值
print(v)报错:TypeError: 'int' object is not iterable
解决:明确是否需要遍历单个值,如果要批量处理,确保对象是可迭代的:
# 如需遍历多个值,直接使用字典的可迭代方法
for v in my_dict.values(): # values() 是可迭代对象
print(v) # 输出:1、2可通过 collections.abc.Iterable 验证:
from collections.abc import Iterable
print(isinstance([1, 2, 3], Iterable)) # True(列表可迭代)
print(isinstance(123, Iterable)) # False(整数不可迭代)
print(isinstance("hello", Iterable)) # True(字符串可迭代)“Object is not iterable” 错误的核心是:操作对象不具备可迭代特性,却被用于需要迭代的场景。
#Python