修复 Python Int Object Is Not Iterable 错误
Haider Ali
2023年10月10日
此错误本身是不言自明的。 'int' object is not iterable
,它清楚地表明你不能在整数上运行迭代。整数是单个数字,而不是可迭代的列表。让我们看一些例子。
修复 Python 中的 'int' object is not iterable
错误
任何返回或存储整数的东西都是不可迭代的。这是常识。如果你不熟悉它,让我们了解一下 python 中的迭代。迭代可以在列表上完成,而不是在整数上。例如,你不能在整数上运行循环进行迭代;这没有任何意义。看看下面的代码。
# integer
number = 123
# loop over an integer
for i in number:
print(i)
运行上面的代码会给你同样的错误,你试图避免。在上面的代码中,number
是一个具有单个值 123
的整数。你不能在它上面运行一个循环。如果你对数据类型及其相关功能感到困惑,你可以通过查找魔术方法轻松解决它。在这种情况下,我们将使用一个整数。看一看。
# integer
number = 123
# built-in / magic methods of an integer
print(dir(number))
上述代码的输出将如下所示。
[
"__abs__",
"__add__",
"__and__",
"__class__",
"__cmp__",
"__coerce__",
"__delattr__",
"__div__",
"__divmod__",
"__doc__",
"__float__",
"__floordiv__",
"__format__",
"__getattribute__",
"__getnewargs__",
"__hash__",
"__hex__",
"__index__",
"__init__",
"__int__",
"__invert__",
"__long__",
"__lshift__",
"__mod__",
"__mul__",
"__neg__",
"__new__",
"__nonzero__",
"__oct__",
"__or__",
"__pos__",
"__pow__",
"__radd__",
"__rand__",
"__rdiv__",
"__rdivmod__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__rfloordiv__",
"__rlshift__",
"__rmod__",
"__rmul__",
"__ror__",
"__rpow__",
"__rrshift__",
"__rshift__",
"__rsub__",
"__rtruediv__",
"__rxor__",
"__setattr__",
"__sizeof__",
"__str__",
"__sub__",
"__subclasshook__",
"__truediv__",
"__trunc__",
"__xor__",
"bit_length",
"conjugate",
"denominator",
"imag",
"numerator",
"real",
]
如你所见,你在上面的列表中找不到迭代器方法。让我们看看列表有什么不同。
# list
lst = [1, 2, 3]
# loop over a list
for j in lst:
print(j)
# built-in /magic methods of a list
print(dir(lst))
上面的代码不会给出任何错误。你可以遍历列表。如果你运行上述代码,你还会注意到其中的 _iter_
函数,说明你可以在列表上使用迭代。
作者: Haider Ali
Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.
LinkedIn