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

yipeiwu_com5年前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多线程与GIL

python 多线程效率 在一台8核的CentOS上,用python 2.7.6程序执行一段CPU密集型的程序。 import time def fun(n):#CPU密集型的程序...

Python排序搜索基本算法之插入排序实例分析

Python排序搜索基本算法之插入排序实例分析

本文实例讲述了Python排序搜索基本算法之插入排序。分享给大家供大家参考,具体如下: 插入排序生活中非常常见,打扑克的时候人的本能就在用插入排序:把抽到的一张插入到手上牌的正确位置上。...

Python使用遗传算法解决最大流问题

Python使用遗传算法解决最大流问题

本文为大家分享了Python遗传算法解决最大流问题,供大家参考,具体内容如下 Generate_matrix def Generate_matrix(x,y): import...

详解在Python和IPython中使用Docker

现在Docker是地球上最炙手可热的项目之一,就意味着人民实际上不仅仅是因为这个才喜欢它。 话虽如此,我非常喜欢使用容器,服务发现以及所有被创造出的新趣的点子和领域来切换工作作为范例。...

pandas的连接函数concat()函数的具体使用方法

pandas的连接函数concat()函数的具体使用方法

concat()函数的具体用法 pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,...