TypeError:’int’ 类型的参数在 Python 中不可迭代

目录

TypeError: ‘numpy.int64’ object is not iterable in Python

  1. TypeError:’int’ 类型的参数在 Python 中不可迭代
  2. TypeError: ‘numpy.int64’ 对象在 Python 中不可迭代
  3. TypeError: ‘int’ 对象在 Python 中不可迭代
  4. TypeError: ‘type’ 对象在 Python 中不可迭代

确保根据您的错误消息单击正确的副标题。

类型错误:’int’ 类型的参数在 Python 中不可迭代

当我们将成员资格测试运算符(in 和 not in)与整数值一起使用时,会出现 Python“TypeError: argument of type ‘int’ is not iterable”。

要解决错误,请更正分配或将 int 转换为字符串。

int 类型的 typeerror 参数不可迭代

下面是错误如何发生的示例。

主程序
my_str = 15 # ⛔️ TypeError: argument of type 'int' is not iterable print('a' in my_str)

我们尝试使用
具有整数值的
成员资格测试运算符
并得到错误。

您可能打算将运算符与可迭代对象一起使用,例如字符串或列表。

将整数转换为字符串或使用列表

解决错误的一种方法是将整数转换为字符串。

主程序
my_str = 15 print('a' in str(my_str)) # 👉️ False print('5' in str(my_str)) # 👉️ True

字符串是可迭代的,因此将整数转换为字符串可以解决问题。

追踪变量被分配整数的位置

但是,解决错误的最佳方法是追踪变量在何处被分配了 int 并更正分配。

例如,如果变量存储了意外类型的值,您可以重新分配该变量。

主程序
my_list = 15 if not isinstance(my_list, list): my_list = [] print('a' in my_list) # 👉️ False

我们检查变量是否my_list没有存储列表,如果没有,我们在使用in运算符之前将其设置为空列表。

您可以将此方法用于任何其他对象,例如strdicttuple等。

主程序
my_str = 15 if not isinstance(my_str, str): my_str = "" print('a' in my_str) # 👉️ False

如果变量不是字符串,我们将其设置为空字符串。

使用前检查值是否为整数in

或者,您可以在使用or
运算符之前
检查该值是否不是
intinnot in

主程序
my_str = 15 if not isinstance(my_str, int): print('a' in my_str) else: # 👇️ this runs print('value is an integer')

我们检查该值是否不是该类的实例int,如果不是,我们使用运算in符来测试成员资格。

但是,更安全的做法是检查值是否属于预期类型,例如 a str、 alist或 a dict

主程序
if isinstance(my_list, list): print('a' in my_list) else: print('value is not a list')

我们的if语句检查值是否是类的实例list,如果是,我们使用in运算符。

in 运算符测试成员资格。例如,如果是 的成员
,则
x in s计算为,否则计算为TruexsFalse

主程序
my_str = 'hello world' print('world' in my_str) # 👉️ True print('another' in my_str) # 👉️ False

xnot in返回ins的否定xs

所有内置序列和集合类型都支持inandnot in运算符。

与字典一起使用时,运算符会检查对象中是否存在指定的键dict

目录

  1. TypeError: ‘numpy.int64’ 对象在 Python 中不可迭代
  2. TypeError: ‘int’ 对象在 Python 中不可迭代
  3. TypeError: ‘type’ 对象在 Python 中不可迭代

TypeError: ‘numpy.int64’ 对象在 Python 中不可迭代

Python“TypeError: ‘numpy.int64’ object is not iterable”发生在我们尝试遍历整数或将整数传递给内置函数(如 或 )
sum()min()

要解决错误,请迭代整数数组或将可迭代对象传递给内置方法。

typeerror-numpy-int64-object-is-not-iterable

下面是错误如何发生的示例。

主程序
import numpy as np my_int = np.int64(25) # ⛔️ TypeError: 'numpy.int64' object is not iterable for i in my_int: print(i)

我们试图迭代导致错误的 numpy 整数值。

这是错误如何发生的另一个示例。

主程序
import numpy as np arr = np.array([1, 2, 3]) # ⛔️ TypeError: 'numpy.int64' object is not iterable for i in arr[2]: print(i)

index 处的数组元素2是一个整数,所以我们不能遍历它。

遍历一系列 numpy 整数

我们可以使用range()内置函数迭代一个范围。

主程序
import numpy as np arr = np.array([1, 2, 3]) for i in range(arr[2]): print(i) # 👉️ 0, 1, 2

如果需要遍历数组,请使用基本的 for 循环。

主程序
import numpy as np arr = np.array([1, 2, 3]) for i in arr: print(i) # 👉️ 1, 2, 3

range函数通常用于在for 循环中循环特定次数,并采用以下参数:

姓名 描述
start 表示范围开始的整数(默认为0
stop 向上,但不包括提供的整数
step 范围将由每 N 个数字组成,从startstop(默认为1

将整数传递给期望可迭代的函数

错误的另一个常见原因是将整数传递给内置构造函数,例如list()
dict()
tuple()
set()

这是一个例子。

主程序
import numpy as np int_1 = np.int64(25) int_2 = np.int64(50) # ⛔️ TypeError: 'numpy.int64' object is not iterable result = sum(int_1, int_2)

像sum()
max()这样的函数min()一个可迭代对象作为参数,所以我们不能直接将 NumPy 整数传递给它。

相反,将 NumPy 整数包装到列表或数组中。

主程序
import numpy as np int_1 = np.int64(25) int_2 = np.int64(50) result = sum([int_1, int_2]) print(result) # 👉️ 75

或者,您可以使用 NumPy 数组。

主程序
import numpy as np int_1 = np.int64(25) int_2 = np.int64(50) arr = np.array([int_1, int_2]) result = sum(arr) print(result) # 👉️ 75

以下 4 次对内置构造函数的调用导致错误。

主程序
import numpy as np arr = np.array([1, 2, 3]) # ⛔️ TypeError: 'numpy.int64' object is not iterable list(arr[0]) dict(arr[0]) tuple(arr[0]) set(arr[0])

要解决错误,我们必须更正赋值并找出整数值的来源。

以下是使用 4 个内置函数的工作示例。

主程序
l = list(['a', 'b', 'c']) print(l) # 👉️ ['a', 'b', 'c'] d = dict(name='Bobby Hadz', age=30) print(d) # 👉️ {'name': 'Bobby Hadz', 'age': 30} t = tuple([1, 2, 3]) print(t) # 👉️ (1, 2, 3) s = set(['a', 'b', 'a']) print(s) # 👉️ {'a', 'b'}

您必须找出整数值的来源并更正分配。

如果您需要对索引和当前项进行迭代,请使用该
enumerate()函数。

主程序
import numpy as np arr = np.array([1, 2, 3]) for idx, el in enumerate(arr): print(idx, el) # 👉️ 0 1, 1 2, 2 3

如果需要检查对象是否可迭代,请使用
try/except 语句

主程序
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 NumPy integer to the iter() function,
the except block is run.

main.py
import numpy as np arr = np.array([1, 2, 3]) try: my_iterator = iter(arr[0]) for i in my_iterator: print(i) except TypeError as te: print(te) # 👉️ 'numpy.int64' 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.

# Table of Contents

  1. TypeError: ‘int’ object is not iterable in Python
  2. TypeError: ‘type’ object is not iterable in Python

# TypeError: ‘int’ object is not iterable in Python

The Python “TypeError: ‘int’ object is not iterable” occurs when we try to
iterate over an integer or pass an integer to a built-in function like, sum(),
list() or tuple().

To solve the error, use the range() built-in function to iterate over a
range or pass a list of integers to the function.

typeerror int 对象不可迭代

Here is an example of how the error occurs.

main.py
num = 10 # ⛔️ TypeError: 'int' object is not iterable for i in num: print(i)

We are trying to iterate over an integer, but integers are not iterable.

# Iterating over a range

We can use the range() built-in function to iterate over a range.

main.py
num = 10 for i in range(num): print(i) # 👉️ 0, 1, 2, ... 8, 9

The range function is commonly used for looping
a specific number of times in for loops and
takes the following parameters:

Name Description
start An integer representing the start of the range (defaults to 0)
stop Go up to, but not including the provided integer
step Range will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is
considered to be the value for the stop parameter.

If values for the start and stop parameters are provided, the start value
is inclusive, whereas the stop value is exclusive.

main.py
num = 5 for i in range(1, num): print(i) # 👉️ 1, 2, 3, 4

# Handling the error in a try/except

If you need to handle the error, use a try/except statement.

main.py
num = 5 try: for i in num: print(i) except TypeError: # The object is not iterable # <class 'int'> print('The object is not iterable') print(type(num))

The try statement tries to iterate over the value and if an exception is
raised, the except block runs.

You can print the value and its type in the except block to debug your code.

# Calling a built-in function with an integer instead of an iterable

The error is also caused if we pass an integer to built-in functions like
sum(), max() and min().

main.py
int_1 = 10 int_2 = 20 # ⛔️ TypeError: 'int' object is not iterable result = sum(int_1, int_2)

These functions take an iterable as an argument and cannot be called with an
integer directly.

Instead, pass a list containing the integers as an argument to the function.

main.py
int_1 = 10 int_2 = 20 # ⛔️ TypeError: 'int' object is not iterable result = sum([int_1, int_2]) print(result) # 👉️ 30

Another common cause of the error is passing an integer to the built-in
constructors, e.g. list(), dict(), tuple() and set().

The following 4 calls to the built-in constructors cause the error.

main.py
num = 10 # ⛔️ TypeError: 'int' object is not iterable list(num) dict(num) tuple(num) set(num)

To solve the error, we have to correct the assignment and figure out where the
integer value is coming from.

Here are working examples of using the 4 built-ins.

main.py
l = list(['a', 'b', 'c']) print(l) # 👉️ ['a', 'b', 'c'] d = dict(name='Bobby Hadz', age=30) print(d) # 👉️ {'name': 'Bobby Hadz', 'age': 30} t = tuple([1, 2, 3]) print(t) # 👉️ (1, 2, 3) s = set(['a', 'b', 'a']) print(s) # 👉️ {'a', 'b'}

You have to figure out where the integer value came from and correct the
assignment.

# The error is commonly caused when using len()

The error is commonly caused when using the len() built-in function.

main.py
my_str = 'hello' # ⛔️ TypeError: 'int' object is not iterable for i in len(my_str): print(i)

The len function returns an integer that represents the length of the
sequence.

If you need to iterate that many times, you can pass the result to the range()
function.

main.py
my_str = 'hello' for i in range(len(my_str)): print(i) # 👉️ 0, 1, 2, 3, 4

If you need to iterate with both the index and the current character or element,
use the enumerate() function.

main.py
my_str = 'hello' for idx, c in enumerate(my_str): print(idx, c) # 👉️ 0 h, 1 e, 2 l... my_list = ['a', 'b', 'c'] for idx, el in enumerate(my_list): print(idx, el) # 👉️ 0 a, 1 b, 2 c

If you need to check if an object is iterable, use a try/except statement.

main.py
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 an integer to the iter() function, the
except block is run.

main.py
my_int = 100 try: my_iterator = iter(my_int) for i in my_iterator: print(i) except TypeError as te: print(te) # 👉️ 'int' 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.

# TypeError: ‘type’ object is not iterable in Python

The Python “TypeError: ‘type’ object is not iterable” occurs when we try to
iterate over a class that is not iterable, e.g. forget to call the range()
function.

To solve the error, make the class iterable by implementing the __iter__()
method.

typeerror 类型对象不可迭代

Here is an example of how the error occurs when the range function.

main.py
# ⛔️ TypeError: 'type' object is not iterable for i in range: print(i)

We forgot to call the range function which caused the error.

If you use the range function, make sure to call it.

main.py
for i in range(0, 3): # 👉️ 0, 1, 2 print(i)

The range class is commonly used for looping a
specific number of times in for loops and takes the following parameters:

Name Description
start An integer representing the start of the range (defaults to 0)
stop Go up to, but not including the provided integer
step Range will consist of every N numbers from start to stop (defaults to 1)

If you only pass a single argument to the range() constructor, it is
considered to be the value for the stop parameter.

If values for the start and stop parameters are provided, the start value is inclusive, whereas the stop value is exclusive.

# Iterating over a class that doesn’t implement the __iter__ method

You will also get the error if you try to iterate over a class that doesn’t
implement the __iter__() method.

main.py
class Counter: pass # ⛔️ TypeError: 'type' object is not iterable for c in Counter: print(c)

If you need to make the class iterable, implement the __iter__ method.

main.py
class Counter: def __init__(self, start, stop): self.current = start - 1 self.stop = stop def __iter__(self): return self def __next__(self): self.current += 1 if self.current < self.stop: return self.current raise StopIteration for c in Counter(0, 4): print(c) # 👉️ 0, 1, 2, 3

The __iter__() method is implicitly called at the start of loops and returns
the iterator object.

The __next__() method is implicitly called at each loop increment and returns
the next value.

# Checking if the object is iterable

If you need to check if an object is iterable, use a try/except statement.

main.py
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 class to the iter() function, the
except block is run.

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.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: