Python 迭代,for...in遍歷,迭代原理與應(yīng)用示例
本文實(shí)例講述了Python 迭代,for...in遍歷,迭代原理與應(yīng)用。分享給大家供大家參考,具體如下:
迭代是訪問集合元素的一種方式。什么時候訪問元素,什么時候再迭代,比一次性取出集合中的所有元素要節(jié)約內(nèi)存。特別是訪問大的集合時,用迭代的方式訪問,比一次性把集合都讀到內(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對象必須實(shí)現(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()會調(diào)用對象的__iter__方法
# print("判斷classmate_iterator是否是迭代器:", isinstance(classmate_iterator, Iterator))
# print(next(classmate_iterator)) # next()會調(diào)用對象的__next__方法
for name in classmate: # 遍歷時會先調(diào)用classmate的__iter__方法(必須返回Iterator對象)。
print(name) # 遍歷出的name就是返回的Iterator對象的__next__方法的返回值
time.sleep(1) # 當(dāng)__next__拋出StopIteration異常時,for遍歷會停止迭代
運(yùn)行結(jié)果:
老王
王二
張三
demo.py(迭代的應(yīng)用):
li = list(可迭代對象) # 將可迭代對象轉(zhuǎn)換成list類型。 底層就是通過迭代實(shí)現(xiàn)的。
print(li)
tp = tuple(可迭代對象) # 將可迭代對象轉(zhuǎn)換成tuple類型。
print(tp)
# for ... in 可迭代對象 # for遍歷也是通過迭代實(shí)現(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對象必須實(shí)現(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) # 將可迭代對象轉(zhuǎn)換成list類型。 底層就是通過迭代實(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對象必須實(shí)現(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("張三")
tp = tuple(classmate) # 將可迭代對象轉(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)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
- 深入解析Python中的list列表及其切片和迭代操作
- Python迭代用法實(shí)例教程
- Python編程實(shí)現(xiàn)二分法和牛頓迭代法求平方根代碼
- python迭代dict的key和value的方法
- 舉例講解如何在Python編程中進(jìn)行迭代和遍歷
- Python用zip函數(shù)同時遍歷多個迭代器示例詳解
- python 循環(huán)while和for in簡單實(shí)例
- 在Python中,不用while和for循環(huán)遍歷列表的實(shí)例
- 對python For 循環(huán)的三種遍歷方式解析
- python中for用來遍歷range函數(shù)的方法
- python中for語句簡單遍歷數(shù)據(jù)的方法
相關(guān)文章
django頁面跳轉(zhuǎn)問題及注意事項(xiàng)
這篇文章主要介紹了django頁面跳轉(zhuǎn)問題及注意事項(xiàng),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Linux安裝Python3如何和系統(tǒng)自帶的Python2并存
這篇文章主要介紹了Linux安裝Python3如何和系統(tǒng)自帶的Python2并存,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
Python實(shí)現(xiàn)在數(shù)字中添加千位分隔符的方法小結(jié)
在數(shù)據(jù)處理和數(shù)據(jù)可視化中,經(jīng)常需要對大數(shù)值進(jìn)行格式化,其中一種常見的需求是在數(shù)字中添加千位分隔符,本文為大家整理了三種常見方法,希望對大家有所幫助2024-01-01
python中urllib.request和requests的使用及區(qū)別詳解
這篇文章主要介紹了python中urllib.request和requests的使用及區(qū)別詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

