python isinstance 可迭代对象
时间: 2023-09-03 13:11:55 浏览: 62
在 Python 中,可以使用 `isinstance()` 函数来检查一个对象是否是一个可迭代对象。一个可迭代对象是指可以使用迭代器进行遍历的对象,例如列表、元组、字典、集合、生成器等。在 `isinstance()` 函数中,可以将要检查的对象作为第一个参数,将 `collections.abc.Iterable` 类作为第二个参数,如果返回 `True`,则表示该对象是一个可迭代对象。示例如下:
```python
from collections.abc import Iterable
lst = [1, 2, 3]
print(isinstance(lst, Iterable)) # True
tpl = (4, 5, 6)
print(isinstance(tpl, Iterable)) # True
dct = {'a': 1, 'b': 2}
print(isinstance(dct, Iterable)) # True
st = {7, 8, 9}
print(isinstance(st, Iterable)) # True
gen = (i for i in range(3))
print(isinstance(gen, Iterable)) # True
num = 10
print(isinstance(num, Iterable)) # False
```
在上面的示例中,我们使用了 `isinstance()` 函数检查了不同类型的对象是否是可迭代对象。其中,列表、元组、字典、集合、生成器都是可迭代对象,而整数不是可迭代对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)