Python 迭代,for...in遍历,迭代原理与应用示例

yipeiwu_com6年前Python基础

本文实例讲述了Python 迭代,for...in遍历,迭代原理与应用。分享给大家供大家参考,具体如下:

迭代是访问集合元素的一种方式。什么时候访问元素,什么时候再迭代,比一次性取出集合中的所有元素要节约内存。特别是访问大的集合时,用迭代的方式访问,比一次性把集合都读到内存要节省资源。

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对象必须实现__iter__方法"""
    return self # __iter__方法必须返回一个Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循环遍历出的变量值
  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类型。 底层就是通过迭代实现的。
print(li)
tp = tuple(可迭代对象)    # 将可迭代对象转换成tuple类型。
print(tp)
# for ... in 可迭代对象     # for遍历也是通过迭代实现的

如上例改写如下:

示例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对象必须实现__iter__方法"""
    return self # __iter__方法必须返回一个Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循环遍历出的变量值
  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类型。 底层就是通过迭代实现的。
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对象必须实现__iter__方法"""
    return self # __iter__方法必须返回一个Iterator(既有__iter__方法,又有__next__方法)
  # __next__的返回值就是for循环遍历出的变量值
  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)  # 将可迭代对象转换成tuple类型。
print(tp)

输出:

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

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python实现SMTP发送邮件详细教程

Python实现SMTP发送邮件详细教程

简介 Python发送邮件的教程本人在网站搜索的时候搜索出来了一大堆,但是都是说了一大堆原理然后就推出了实现代码,我测试用给出的代码进行发送邮件时都不成功,后面找了很久才找到原因,这都是...

Django models.py应用实现过程详解

Django models.py应用实现过程详解

编写 models.py 文件 from django.db import models # Create your models here. class User_info(mod...

Python学习笔记之open()函数打开文件路径报错问题

Python学习笔记之open()函数打开文件路径报错问题

要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符,标示符'r'表示读。 >>> f = open('D:/test.tx...

Python实现模拟分割大文件及多线程处理的方法

本文实例讲述了Python实现模拟分割大文件及多线程处理的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python #--*-- coding:utf-8...

30秒学会30个超实用Python代码片段【收藏版】

许多人在数据科学、机器学习、web开发、脚本编写和自动化等领域中都会使用Python,它是一种十分流行的语言。 Python流行的部分原因在于简单易学。 本文将简要介绍30个简短的、...