温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-13 13:16:15 来源:脚本之家 阅读:177 作者:houyanhua1 栏目:开发技术

本文实例讲述了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程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI