修復 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