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

首頁 > 編程 > Python > 正文

Python 中迭代器與生成器實(shí)例詳解

2020-02-23 04:29:24
字體:
供稿:網(wǎng)友

Python 中迭代器與生成器實(shí)例詳解

本文通過針對(duì)不同應(yīng)用場(chǎng)景及其解決方案的方式,總結(jié)了Python中迭代器與生成器的一些相關(guān)知識(shí),具體如下:

1.手動(dòng)遍歷迭代器

應(yīng)用場(chǎng)景:想遍歷一個(gè)可迭代對(duì)象中的所有元素,但是不想用for循環(huán)

解決方案:使用next()函數(shù),并捕獲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.代理迭代

應(yīng)用場(chǎng)景:想直接在一個(gè)包含有列表、元組或其他可迭代對(duì)象的容器對(duì)象上執(zhí)行迭代操作

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

示例:

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):    #將迭代請(qǐng)求傳遞給內(nèi)部的_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.反向迭代

應(yīng)用場(chǎng)景:想要反向迭代一個(gè)序列

解決方案:使用內(nèi)置的reversed()函數(shù)或者在自定義類上實(shí)現(xiàn)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  #常規(guī)迭代  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.有選擇的迭代

應(yīng)用場(chǎng)景:想遍歷一個(gè)可迭代對(duì)象,但是對(duì)它開始的某些元素并不感興趣,想跳過

解決方案:使用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.同時(shí)迭代多個(gè)序列

應(yīng)用場(chǎng)景:想同時(shí)迭代多個(gè)序列每次分別從一個(gè)序列中取一個(gè)元素

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 林芝县| 获嘉县| 桦南县| 吉安县| 满洲里市| 武陟县| 攀枝花市| 苍南县| 巴青县| 青海省| 肥城市| 肥西县| 饶阳县| 金秀| 会理县| 奉化市| 荆门市| 松滋市| 正定县| 大荔县| 明水县| 高青县| 得荣县| 明星| 石林| 阿图什市| 汝州市| 平塘县| 宿迁市| 大石桥市| 西宁市| 镇平县| 米脂县| 资兴市| 无棣县| 盐亭县| 高台县| 黑山县| 宁城县| 昔阳县| 叶城县|