迭代器
Posted jiaqi-666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了迭代器相关的知识,希望对你有一定的参考价值。
迭代器
使用dir来查看该数据包含了那些方法
print(dir(str)) 运行结果: [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
用来遍历列表,字符串,元祖....可迭代对象
可迭代对象: Iterable, 里面有__iter__()可以获取迭代器, 没有__next__()
迭代器: Iterator, 里面有__iter__()可以获取迭代器, 还有__next__()
lst = [1, 2, 3] it = lst.__iter__() print("__iter__" in dir(it)) print("__next__" in dir(it)) from collections import Iterable # 可迭代对象 from collections import Iterator # 迭代器 print(isinstance(lst, Iterable)) print(isinstance(lst, Iterator)) print(isinstance(it, Iterable)) print(isinstance(it, Iterator))
迭代器特点:
1. 只能向前
2. 惰性机制
3. 省内存(生成器)
for循环的内部机制
1. 首先获取到迭代器
2. 使用while循环获取数据
3. it.__next__()来获取数据
4. 处理异常 try:xxx except StopIteration:
lst = ["大", "家", "好"] a = lst.__iter__() while True: try: s = a.__next__() print(s) except StopIteration: break
以上是关于迭代器的主要内容,如果未能解决你的问题,请参考以下文章