ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

python基础语法学习: 迭代器

2026/8/28 7:58:39 拓冰建站 浏览量
python基础语法学习: 迭代器 文章目录迭代器获取迭代器的方案iter()__iter__()从迭代器中拿到数据的方案next()__next__()模拟for循环的工作原理迭代器的特性迭代器首先请看以下代码:forcinhello:print(c)要使用for c in这种形式进行遍历, 对象一定要是可迭代的东西(iterable), 例如: str, list, tuple, dict, set, open()可迭代的数据类型都会提供一个叫迭代器的东西, 这个迭代器可以帮我们把数据类型种的所有数据一个一个拿出来获取迭代器的方案iter()iter()内置函数可以直接拿到迭代器ititer(hello)print(it)# str_ascii_iterator object at 0x00000280FF552530__iter__()__iter__()特殊方法shelloits.__iter__()print(it)# str_ascii_iterator object at 0x0000011BEDB92530从迭代器中拿到数据的方案next()使用next()内置函数ititer(hello)print(next(it))print(next(it))print(next(it))print(next(it))print(next(it))print(next(it))# 报错, StopIteration注意: 这里迭代器超出对象的范围就会报错迭代器停止了,就不可以从迭代器中拿数据了__next__()shelloits.__iter__()print(it.__next__())print(it.__next__())print(it.__next__())print(it.__next__())print(it.__next__())print(it.__next__())# 报错 StopIteration模拟for循环的工作原理sheloititer(s)whileTrue:try:datanext(it)print(data)exceptStopIteration:break下面的代码是一段错误代码forcin123:passfor循环中一定是要拿迭代器的, 所有不可迭代的东西不能用for循环迭代器统一了所有不同数据类型的遍历方式迭代器本身也是可迭代的shello worldits.__iter__()forminit:print(m)迭代器的特性迭代器只能向前不能反复迭代器本身是可迭代的迭代器特别节省内存惰性机制