码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器

时间:2020-07-22 23:30:35      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:val   encoding   for   调用   call   res   ret   优点   多行   

迭代器:

1, 什么是迭代器
器: 工具
迭代: 是一个重复的过程, 但是每次重复都是基于上一次的结果而来的

name = ["egon", "lqz", "tank"]

count = 1
while count < len(names):
   print(nmes[count])
   count += 1

迭代器: 就是一种不依赖索引的取值工具

2, 为何要有迭代器
特性:
1, 是一种通用的迭代取值方案
2, 惰性计算, 节省内存

3, 如何用迭代器

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}

dic_iterator = dic.__iter__()
res1 = dic_iterator.__next__()
print(res1)
res2 = dic_iterator.__next__()
print(res2)
res = dic_iterator.__next__()
print(res)

dic_iterator.__next__()  # StopIteration  抛出异常

while True:
   try:
      res = dic_iterator.__next__()
      print(res)
   except StopIteration:  # 解决抛出异常
      break

可迭代对象与迭代器对象
内置有__iter__方法的类型称之为: 可迭代对象 / 类型
字典
集合
文件对象(也是迭代器对象)
字符串
列表
元祖
迭代器对象: 内置有__iter_, __next___方法

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}

dic_iterator = dic.__iter__()
dic_iterator.__next__()

for工作循环原理

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}

dic_iterator = dic.__iter__()
while True:
   try:
      res = dic_iterator.__next__()
      print(res)
   except StopIteration:
      break

for k in dic:
   print(k)
步骤1
dic_iterator = dic.__iter__()
步骤2
k = dic_iterator.__next__(), 执行循环体代码
步骤3
循环往复,直到抛出异常,for循环会帮我们捕捉异常结束循环

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}
dic_iterator = dic.__iter__()
for k in dic_iterator:
   print(k)

print(dic_iterator)

四:基于同一迭代器的重复取值,效果如何????
示例1:

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}
dic_iterator = dic.__iter__()

while True:
   try:
      res = dic_iterator.__next__()
      print(res)
   except StopIteration:
      break

while True:
   try:
      res = dic_iterator.__next__()
      print(res)
   except StopIteration:
      break

示例2:

dic = {"name": "egon", ‘age‘: 18, ‘gender‘: "male"}
for k in dic:  # dic.__iter__()
   print(k)

for k in dic:  # dic.__iter__()
   print(k)

自定义迭代器来实现惰性计算, 从而达到节省内存的效果

生成器

什么是生成器
但凡是函数内出现了yield关键字, 调用函数将不会执行函数体代码, 会得到一个返回值,
该返回值就是我们自定义的迭代器, 称之为生成器

def func():
   print("hello")
   yield 1
   print("hello")
   yield 2
   print("hello")
   yield 3


g = func()
print(g)  # 生成器本身就是一个迭代器
res = next(g)
print(res)

res = next(g)
print(res)

res = next(g)
print(res)


yield与return

相同点: 都可以用来返回值
不同点:
return只能返回一次值, 函数就立刻结束了
yield能返回多次值, yield可以挂起函数

案例

def func():
   res = 0
   while True:
      res += 1
      yield res


g = func()
for i in g:
   print(i)

总结迭代器的优缺点
优点:
1, 是一种通用的迭代取值方案
2, 惰性计算, 节省内存

缺点:
1, 取值不如索引, key的取值方式灵活
2, 取值是一次性的, 只能往后取, 不能预估值得个数

案例:

def my_range(start, stop, step=1):
   while start < stop:
      yield start
      start += stop


for i in my_range(1, 5, 2):
   print(i)

生成式:

列表生成式
l = [i ** 2 for i in range(5) if i > 2]
print(l)
names = [‘lqz_sb‘, ‘yj_sb‘, ‘jason_sb‘, ‘egon‘]
l = [name for name in names if name.endswith("sb")]
print(l)
集合生成式
res = {i for i in range(3)}

print(res)

字典生成式
res = {f"k{i}": i ** 2 for i in range(5)}

print(res)

生成器表达式
res(i for i in range(5))
print(res, type(res))
nums = (i for i in range(200000))
res = sum(nums)
print(res)
with open("a.txt", mode=‘rt‘, encoding=‘utf-8‘)as f:
  # data = f.read()
  # print(len(data))

  # res = 0
  # for line in f:
  #    res += len(line)
  # res = sum(len(line) for line in f)

   res = sum(len(line) for line in f)
   print(res)

内置函数
print(abs(-7)) #abs数值取正

print(all([True,11,0]))
print(all[])#all不能空,其次是判定内部数据是否全部为真

print(any([True,False,0]))
print(any([]))#any一样不能取空,其次与or一样的意思只需其中一个值为真就会是True

print(callable(len))#callable指这个函数是否能用

print(chr(90))
print(ord(‘z‘))#chr 和 ord相互翻译例如90的代码是z,z的实体数据是90

print(divmod(10,3))

divmod指除法,结果以括号形式表现

l = [1,2,3]
print(dir(l))

dir表示这个列表能用哪一些内置函数

res = eval(‘{‘k1‘:111}\n‘)
print(res[‘k1‘])#将以文件数据类型的方式写入文件,多行可以用换行符\n

迭代器

标签:val   encoding   for   调用   call   res   ret   优点   多行   

原文地址:https://www.cnblogs.com/lgh8023/p/13363408.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!