本文實例講述了Python 迭代,for...in遍歷,迭代原理與應用。分享給大家供大家參考,具體如下:
迭代是訪問集合元素的一種方式。什么時候訪問元素,什么時候再迭代,比一次性取出集合中的所有元素要節(jié)約內(nèi)存。特別是訪問大的集合時,用迭代的方式訪問,比一次性把集合都讀到內(nèi)存要節(jié)省資源。
demo.py(迭代,遍歷):
import timefrom collections import Iterablefrom 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對象必須實現(xiàn)__iter__方法""" return self # __iter__方法必須返回一個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異常時,for遍歷會停止迭代classmate = Classmate()classmate.add("老王")classmate.add("王二")classmate.add("張三")# print("判斷classmate是否是可以迭代的對象:", isinstance(classmate, Iterable))# classmate_iterator = iter(classmate) # iter()會調用對象的__iter__方法# print("判斷classmate_iterator是否是迭代器:", isinstance(classmate_iterator, Iterator))# print(next(classmate_iterator)) # next()會調用對象的__next__方法for name in classmate: # 遍歷時會先調用classmate的__iter__方法(必須返回Iterator對象)。 print(name) # 遍歷出的name就是返回的Iterator對象的__next__方法的返回值 time.sleep(1) # 當__next__拋出StopIteration異常時,for遍歷會停止迭代
運行結果:
老王
王二
張三
demo.py(迭代的應用):
li = list(可迭代對象) # 將可迭代對象轉換成list類型。 底層就是通過迭代實現(xiàn)的。
print(li)
tp = tuple(可迭代對象) # 將可迭代對象轉換成tuple類型。
print(tp)
# for ... in 可迭代對象 # for遍歷也是通過迭代實現(xiàn)的
如上例改寫如下:
示例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對象必須實現(xiàn)__iter__方法""" return self # __iter__方法必須返回一個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異常時,for遍歷會停止迭代classmate = Classmate()classmate.add("老王")classmate.add("王二")classmate.add("張三")li = list(classmate) # 將可迭代對象轉換成list類型。 底層就是通過迭代實現(xiàn)的。print(li)
輸出:
新聞熱點
疑難解答