python迭代器与生成器

迭代器与生成器

列表推导式

#打印30以内能被3整除的数, 放到一个列表里
result = [ i for i in range(30) if i%3 == 0]
print(result)

#30以内能被3整除的数的平方
print([ i*i for i in range(30) if i%3 == 0])

#列表里的浮点数保留两位小数, 整数保持原样
lst = [2.43, 6.666,9, 2.2324]
print( [ round(i,2)  for i in lst])

嵌套推导式

print([ i for lst in lst2 for i in lst if i%2 ])

集合推导式

str1 = "asdofiwejfoasidjfowerijf"
print(set(str1))
print({i for i in str1})

字典推导式

str1 = "seofiajweoifksadjfsfss"
result = {i:str1.count(i)  for i in str1}
print(result)
print({j:i  for i,j in result.items()})

q1 = ['a','ab','abc','abcd','abcde']
print([ i.upper() for i in q1 if len(i) >=3])

print([ (x,y)   for x in range(6) if x%2 == 0 for y in range(6) if y%2 == 1])

q4 = {'B':3, 'a':1, 'b':6, 'c':3, 'A':4}
print({i.lower(): q4.get(i.lower(),0) + q4.get(i.upper(),0) for i in q4 })

可迭代对象

实现了 __iter__方法,并且该方法返回一个迭代器,这样子的对象就是可迭代对象

>>> hasattr(a,"__iter__")
True
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> from collections import Iterable
>>> isinstance(a, Iterable)
True
>>> isinstance(1, int)
True
>>> isinstance(a, list)
True

可迭代对象有哪些?
1、容器类型都是可迭代对象
list tuple dict set str
2、range
3、打开的文件

迭代器

任何实现了__iter__()和__next__()都是迭代器
iter() 返回自身
next() 下一个值
for循环中,先调用__iter__获取到一个迭代器
然后再不断的调用__next__ 获取下一个值
for循环中,如果遇到StopIteration,就退出循环

>>> lst = ["a","b","c"]
>>> dir(lst)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> r1 = lst.__iter__()
>>> dir(r1)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__length_hint__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']
>>> r1.__next__()
'a'
>>> r1.__next__()
'b'
>>> 1.__next__()
  File "<stdin>", line 1
    1.__next__()
             ^
SyntaxError: invalid syntax
>>> r1.__next__()
'c'
>>> r1.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> lst
['a', 'b', 'c']
>>> r2 = iter(lst)
>>> r2
<list_iterator object at 0x7f16046e0898>
>>> next(r2)
'a'
>>> next(r2)
'b'
>>> next(r2)
'c'
>>> next(r2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

生成器

懒加载

yeild关键字

关键字处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值