python中可迭代对象的解释及判断方法
什么是可迭代对象
对大多数初学者来说,可迭代这个名词很陌生,但他的另一个说法有一点基础的人一定都不陌生,就是遍历。 在python中,对list、tuple、dict、set、str等类型的数据使用for…in…的循环语法从其中依次拿到数据进行使用,我们把这样的过程称为遍历,也叫迭代。但是,并不是所有的数据类型都可以进行遍历(迭代),我们通过实例来看: 1.列表
# 测试列表是否可迭代
for list1 in [1, 2, 3]:
print(list1,end=)
输出结果
123
2.元组
# 测试元组是否可迭代
for tuple1 in (4, 5, 6):
print(tuple1, end=)
输出结果
456
3.字符串
# 测试字符串是否可迭代
for str in hello world:
print(str, end=)
输出结果
hello world
4.整型
# 测试整型是否可迭代
for int1 in 123:
print(int1, end=)
输出结果
Traceback (most recent call last):
File "A:/py_demo/day_5.py", line 52, in <module>
for int1 in 123:
TypeError: int object is not iterable
Process finished with exit code 1
这里报错就可以看出整型不可以迭代,仔细观察一下报错的内容"TypeError: ‘int’ object is not iterable",这句话的翻译过来就是:整型的对象不可以迭代。
除此以外,还有一种快捷的方法可以判断该数据类型是否可以迭代。
判断方法
利用Iterable
from collections import Iterable
print(isinstance([], Iterable)) # 列表
print(isinstance((), Iterable)) # 元组
print(isinstance(str, Iterable)) # 字符串
print(isinstance(100, Iterable)) # 整型
print(isinstance({
}, Iterable)) # 字典
print(isinstance({
a}, Iterable)) # 集合
输出结果
True True True False True True
这就是一个比较直接的方法
