溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python 迭代,for...in遍歷,迭代原理與應(yīng)用示例

發(fā)布時(shí)間:2020-09-13 13:16:15 來(lái)源:腳本之家 閱讀:186 作者:houyanhua1 欄目:開(kāi)發(fā)技術(shù)

本文實(shí)例講述了Python 迭代,for...in遍歷,迭代原理與應(yīng)用。分享給大家供大家參考,具體如下:

迭代是訪問(wèn)集合元素的一種方式。什么時(shí)候訪問(wèn)元素,什么時(shí)候再迭代,比一次性取出集合中的所有元素要節(jié)約內(nèi)存。特別是訪問(wèn)大的集合時(shí),用迭代的方式訪問(wèn),比一次性把集合都讀到內(nèi)存要節(jié)省資源。

demo.py(迭代,遍歷):

import time
from collections import Iterable
from collections import Iterator
# 有__iter__方法的類是Iterable(可迭代的)。
# 既有__iter__方法又有__next__方法是Iterator(迭代器)。
class Classmate(object):
  def __init__(self):
    self.names = list()
    self.current_num = 0
  def add(self, name):
    self.names.append(name)
  def __iter__(self):
    """Iterable對(duì)象必須實(shí)現(xiàn)__iter__方法"""
    return self # __iter__方法必須返回一個(gè)Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循環(huán)遍歷出的變量值
  def __next__(self):
    if self.current_num < len(self.names):
      ret = self.names[self.current_num]
      self.current_num += 1
      return ret
    else:
      raise StopIteration # 拋出StopIteration異常時(shí),for遍歷會(huì)停止迭代
classmate = Classmate()
classmate.add("老王")
classmate.add("王二")
classmate.add("張三")
# print("判斷classmate是否是可以迭代的對(duì)象:", isinstance(classmate, Iterable))
# classmate_iterator = iter(classmate) # iter()會(huì)調(diào)用對(duì)象的__iter__方法
# print("判斷classmate_iterator是否是迭代器:", isinstance(classmate_iterator, Iterator))
# print(next(classmate_iterator))  # next()會(huì)調(diào)用對(duì)象的__next__方法
for name in classmate: # 遍歷時(shí)會(huì)先調(diào)用classmate的__iter__方法(必須返回Iterator對(duì)象)。
  print(name)  # 遍歷出的name就是返回的Iterator對(duì)象的__next__方法的返回值
  time.sleep(1) # 當(dāng)__next__拋出StopIteration異常時(shí),for遍歷會(huì)停止迭代

運(yùn)行結(jié)果:

老王
王二
張三

demo.py(迭代的應(yīng)用):

li = list(可迭代對(duì)象)    # 將可迭代對(duì)象轉(zhuǎn)換成list類型。 底層就是通過(guò)迭代實(shí)現(xiàn)的。
print(li)
tp = tuple(可迭代對(duì)象)    # 將可迭代對(duì)象轉(zhuǎn)換成tuple類型。
print(tp)
# for ... in 可迭代對(duì)象     # for遍歷也是通過(guò)迭代實(shí)現(xiàn)的

如上例改寫(xiě)如下:

示例1:

class Classmate(object):
  def __init__(self):
    self.names = list()
    self.current_num = 0
  def add(self, name):
    self.names.append(name)
  def __iter__(self):
    """Iterable對(duì)象必須實(shí)現(xiàn)__iter__方法"""
    return self # __iter__方法必須返回一個(gè)Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循環(huán)遍歷出的變量值
  def __next__(self):
    if self.current_num < len(self.names):
      ret = self.names[self.current_num]
      self.current_num += 1
      return ret
    else:
      raise StopIteration # 拋出StopIteration異常時(shí),for遍歷會(huì)停止迭代
classmate = Classmate()
classmate.add("老王")
classmate.add("王二")
classmate.add("張三")
li = list(classmate)  # 將可迭代對(duì)象轉(zhuǎn)換成list類型。 底層就是通過(guò)迭代實(shí)現(xiàn)的。
print(li)

輸出:

['老王', '王二', '張三']

示例2:

class Classmate(object):
  def __init__(self):
    self.names = list()
    self.current_num = 0
  def add(self, name):
    self.names.append(name)
  def __iter__(self):
    """Iterable對(duì)象必須實(shí)現(xiàn)__iter__方法"""
    return self # __iter__方法必須返回一個(gè)Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循環(huán)遍歷出的變量值
  def __next__(self):
    if self.current_num < len(self.names):
      ret = self.names[self.current_num]
      self.current_num += 1
      return ret
    else:
      raise StopIteration # 拋出StopIteration異常時(shí),for遍歷會(huì)停止迭代
classmate = Classmate()
classmate.add("老王")
classmate.add("王二")
classmate.add("張三")
tp = tuple(classmate)  # 將可迭代對(duì)象轉(zhuǎn)換成tuple類型。
print(tp)

輸出:

('老王', '王二', '張三')

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI