日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python学习之迭代器

發布時間:2024/8/1 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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']

判斷某對象是不是可迭代對象,有兩種方法:

  • print(‘__iter__’ in dir(str))
  • from collections import Iterable print(isinstance('abc',iterable) print(isinstance('abc',str))
  • 迭代器定義

    內部含有__iter__且含有__next__方法的對象就是迭代器,遵循迭代器協議

    • 將可迭代對象轉化成迭代器
    s1 = 'abcd' obj_s = s1.__iter__()
    • 將可迭代對象轉化成迭代器
    obj_s = iter(s1) print(obj_s) print(obj_s.__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学习之迭代器的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。