python学习之迭代器
生活随笔
收集整理的這篇文章主要介紹了
python学习之迭代器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
迭代
簡單的說,可將某個數據集內的數據依次取出,叫做迭代
可迭代協議
內部實現的_iter_方法
常見的可迭代對象類型
str,list,tuple,dict,set,range,文件句柄
# 查看str是否可迭代
print(dir(str))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__','__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__','__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']判斷某對象是不是可迭代對象,有兩種方法:
迭代器定義
內部含有__iter__且含有__next__方法的對象就是迭代器,遵循迭代器協議
- 將可迭代對象轉化成迭代器
- 將可迭代對象轉化成迭代器
判斷當前對象是否是迭代器的兩種方法
s1 = 'abc' print('__iter__' in dir(s1)) print('__next__' in dir(s1)) from collections import Iterator l1 = [1,2,3] print(isinstance(l1,Iterator)) l1_obj = l1.__iter__() print(isinstance(l1_obj,Iterator))迭代器的好處
- 節省內存
- 惰性機制
- 單向執行,不可逆
總結
以上是生活随笔為你收集整理的python学习之迭代器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据仓库与数据挖掘相关基础概念
- 下一篇: 2018Android面试宝典