1 迭代器(Iterator)
- Iterable
>>> from collections import Iterable
>>> isinstance([1,2,3],Iterable)
True
總結(jié):凡是可作用于 for 循環(huán)的對象都是 Iterable 類型;
- Iterator
>>> a = [1,2,3,4,5]
>>> f = (x for x in a)
>>> f
<generator object <genexpr> at 0x021379C0>
>>> next(f)
4
>>> next(f)
5
>>> next(f)
6
>>> next(f)
7
>>> next(f)
8
>>> isinstance(f,collections.Iterator)
True
總結(jié):凡是可作用于 next() 函數(shù)的對象都是 Iterator 類型,即迭代器
>>> a=[1,2,3]
>>> b=(1,2,3)
>>> c='abc'
>>> isinstance(a,Iterable)
True
>>> isinstance(b,Iterable)
True
>>> isinstance(c,Iterable)
True
總結(jié): 集合數(shù)據(jù)類型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不過可以 通過 iter() 函數(shù)獲得一個 Iterator 對象。 目的是在使用集合的時候,減少占用的內(nèi)容。
>>> iter(a)
<list_iterator object at 0x02131330>
>>> f=iter(a)
>>> isinstance(f,collections.Iterator)
True
總結(jié):生成器都是 Iterator 對象,但 list 、 dict 、 str 雖然是 Iterable ,卻不是 Iterator 。
把 list 、 dict 、 str 等 Iterable 變成 Iterator 可以使用 iter() 函數(shù)。
2 多線程模擬
- 模擬多任務(wù)(進(jìn)程,線程,協(xié)程)實(shí)現(xiàn)方式之一:協(xié)程
def test1():
while True:
print("--1--")
yield None
def test2():
while True:
print("--2--")
yield None
t1 = test1()
t2 = test2()
while True:
t1.__next__()
t2.__next__()