可迭代:
可迭代的对象:1.生成器2.元组,列表,集合,字典,字符串。
判断一个对象是否是可迭代的:
from collections import Iterable
list1 = [1,4,7,8,9]
f = isinstance("abc",Iterable)
print(f)
# True
f = isinstance(111,Iterable)
print(f)
# False
f = isinstance({1:3},Iterable)
print(f)
# True
# DeprecationWarning: Using or importing the ABCs from 'collections'
# instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
在python 3.8中将会停止使用。
迭代器:
迭代是访问集合元素的一种方式,迭代器是一个可以记住遍历的位置的对象。
迭代器对象从集合中的第一个元素开始访问,知道所有的元素被访问完结束。
迭代器只能前进不能后退。
可以被 next 函数调用并不断返回下一个值的对象称为迭代器:Iterator。
借助 iter 函数将列表等不可迭代的转换为可迭代的,用于列表集合等可迭代的对象。
生成器是迭代器的一种 。
list1 = [1,2,3,3,2,5,6]
# print(next(list1))
# 直接调用next就会爆出TypeError。
list1 = iter(list1)
print(next(list1))
# 1
print(next(list1))
# 2