Python_迭代器&生成器

1、迭代器

(1)简单使用

>>> li=[5,6,7]
>>>
>>> it=iter(li)
>>>
>>> print(it)
<list_iterator object at 0x000002301ABF9A20>
>>>
>>> print(it.__next__())
5
>>>
>>> print(it.__next__())
6
>>>
>>> print(it.__next__())
7
>>>

 

(2)字典的迭代

  默认为字典key的迭代:

a= iter({1:2,3:4})

type(a)

<class 'dict_keyiterator'>

 

字典value的迭代:

>>> a= iter({1:2,3:4}.values())

>>> type(a)

<class 'dict_valueiterator'>

 得到的结果

>>> print(a.__next__())
2
>>> print(a.__next__())
4
>>>

 

(3)next迭代器,next的用法

a = [1,2,3]

>>> a=iter(a)

>>> next(a)

1

>>> next(a)

2

>>> next(a)

3

2、生成器

(1) 简单应用

*注意:推导列表和生成器写法的区分

>>> L = [x * x for x in range(10)]#推导列表的写法
>>> print (L)

[0,
1, 4, 9, 16, 25, 36, 49, 64, 81] >>> g = (x * x for x in range(10))#生成器的写法 >>> print (g) <generator object <genexpr> at 0x000002301AB5FE08>#表示g为生成器 >>>

结果如下:

>>> print (next(g))
0
>>> print (next(g))
1
>>> print (next(g))
4
>>> print (next(g))
9
>>>
>>> for n in g:
...     print (n)
...
16
25
36
49
64
81
>>>

 

 

>>> L = [x for x in range(1,10,2)]
>>> print (L)
[1, 3, 5, 7, 9]
>>> g = (x for x in range(1,10,2))
>>> print (g)
<generator object <genexpr> at 0x000002301AB5FEB8>
>>> print (next(g))
1
>>> print (next(g))
3
>>> print (next(g))
5
>>> print (next(g))
7
>>>
>>> for n in g:     #注意此处的结果
...     print (n)
...
9
>>>

 

(2) yield生成器,相当于next

 

定义yield生成器的方法:

 

>>> def odd():#定义yield生成器的方法
...     print ('step 1')
...     yield 1
...     print ('step 2')
...     yield 3
...     print ('step 3')
...     yield 5
...
>>> 
传入参数后,得到的结果:
>>> o = odd()
>>> print (next(o))
step 1
1
>>> print (next(o))
step 2
3
>>> print (next(o))
step 3
5
>>> 


  >>> for i in o:
  ... print (i)
  ...
  >>>

 

 

posted @ 2018-10-08 12:18  翻滚的小强  阅读(198)  评论(0编辑  收藏  举报