国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 中迭代器與生成器實例詳解

2019-11-25 16:16:53
字體:
來源:轉載
供稿:網友

Python 中迭代器與生成器實例詳解

本文通過針對不同應用場景及其解決方案的方式,總結了Python中迭代器與生成器的一些相關知識,具體如下:

1.手動遍歷迭代器

應用場景:想遍歷一個可迭代對象中的所有元素,但是不想用for循環

解決方案:使用next()函數,并捕獲StopIteration異常

def manual_iter():  with open('/etc/passwd') as f:    try:      while True:        line=next(f)        if line is None:          break        print(line,end='')      except StopIteration:        pass
#test caseitems=[1,2,3]it=iter(items)next(it)next(it)next(it)

2.代理迭代

應用場景:想直接在一個包含有列表、元組或其他可迭代對象的容器對象上執行迭代操作

解決方案:定義一個iter()方法,將迭代操作代理到容器內部的對象上

示例:

class Node:  def __init__(self,value):    self._value=value    self._children=[]  def __repr__(self):    return 'Node({!r})'.fromat(self._value)  def add_child(self,node):    self._children.append(node)  def __iter__(self):    #將迭代請求傳遞給內部的_children屬性    return iter(self._children)
#test caseif __name='__main__':  root=Node(0)  child1=Node(1)  child2=Nide(2)  root.add_child(child1)  root.add_child(child2)  for ch in root:    print(ch)

3.反向迭代

應用場景:想要反向迭代一個序列

解決方案:使用內置的reversed()函數或者在自定義類上實現reversed()

示例1

a=[1,2,3,4]for x in reversed(a):  print(x) #4 3 2 1f=open('somefile')for line in reversed(list(f)):  print(line,end='')#test casefor rr in reversed(Countdown(30)):  print(rr)for rr in Countdown(30):  print(rr)

示例2

class Countdown:  def __init__(self,start):    self.start=start  #常規迭代  def __iter__(self):    n=self.start    while n > 0:      yield n      n -= 1  #反向迭代  def __reversed__(self):    n=1    while n <= self.start:      yield n      n +=1

4.有選擇的迭代

應用場景:想遍歷一個可迭代對象,但是對它開始的某些元素并不感興趣,想跳過

解決方案:使用itertools.dropwhile()

示例1

with open('/etc/passwd') as f:  for line in f:    print(line,end='')

示例2

from itertools import dropwhilewith open('/etc/passwd') as f:  for line in dropwhile(lambda line:line.startwith('#'),f):    print(line,end='')

5.同時迭代多個序列

應用場景:想同時迭代多個序列每次分別從一個序列中取一個元素

解決方案:使用zip()函數

這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

6.不同集合上元素的迭代

應用場景:想在多個對象執行相同的操作,但是這些對象在不同的容器中

解決方案:使用itertool.chain()函數

這里寫圖片描述

7.展開嵌套的序列

應用場景:想將一個多層嵌套的序列展開成一個單層列表

解決方案:使用包含yield from語句的遞歸生成器

示例

from collections import Iterabledef flatten(items,ignore_types=(str,bytes)):  for x in items:    if isinstance(x,Iterable) and not isinstance(x,ignore_types):      yield from flatten(x)    else:      yield x
#test caseitems=[1,2,[3,4,[5,6],7],8]for x in flatten(items):  print(x)

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 依兰县| 金堂县| 嘉鱼县| 扎鲁特旗| 泸水县| 长白| 公安县| 丽水市| 潞西市| 繁昌县| 尤溪县| 洪湖市| 民勤县| 德令哈市| 定襄县| 沁水县| 军事| 大姚县| 分宜县| 墨竹工卡县| 西宁市| 兖州市| 泉州市| 拉萨市| 泰来县| 顺昌县| 于田县| 科技| 新巴尔虎左旗| 永寿县| 大冶市| 孝感市| 云浮市| 宜都市| 同德县| 宣恩县| 桐梓县| 盱眙县| 永和县| 庆安县| 武宁县|