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 Collatz序列实现过程解析

编写一个名为 collatz()的函数,它有一个名为 number 的参数。如果参数是偶数,那么 collatz()就打印出 number // 2, 并返回该值。如果 number 是...

解析Python的缩进规则的使用

Python中的缩进(Indentation)决定了代码的作用域范围。这一点和传统的c/c++有很大的不同(传统的c/c++使用花括号{}符,python使用缩进空格)。 每行代码中开头...

python ceiling divide 除法向上取整(或小数向上取整)的实例

向上取整的方法: 方法1: items = 102 boxsize = 10 num_boxes = (items + boxsize - 1) // boxsize 方法2:...

python获取局域网占带宽最大3个ip的方法

python获取局域网占带宽最大3个ip的方法

本文实例讲述了python获取局域网占带宽最大3个ip的方法。分享给大家供大家参考。具体实现方法如下: import re import urllib url = 'http://a...

python障碍式期权定价公式

早期写的python障碍式期权的定价脚本,供大家参考,具体内容如下 #coding:utf-8 ''' 障碍期权 q=x/s H = h/x H 障碍价格 [1] Down-and-...