python中的Iterable, Iterator,生成器概念
https://nychent.github.io/articles/2016-05/about-generator.cn
这个深刻
谈起Generator, 与之相关的的概念有 - {list, set, tuple, dict} comprehension and container - iterable - iterator - generator fuction and iterator - generator expression
#!/usr/bin/env python # -*- coding: utf-8 -*- # Spawn a Process: Chapter 3: Process Based Parallelism import multiprocessing import time from collections import Iterable, Iterator import dis from itertools import islice x = [1, 2, 3] for i in x: print i y = iter(x) z = iter(x) print dir(x) print dir(y) print next(y) print next(y) print next(z) print next(z) print type(x) print isinstance(x, Iterable) print isinstance(x, Iterator) print type(y) print isinstance(y, Iterable) print isinstance(y, Iterator) class seq(object): def __init__(self): self.gap = 2 self.curr = 1 def __iter__(self): return self def next(self): value = self.curr self.curr += self.gap return value f = seq() print list(islice(f, 0, 10)) def seq(): gap, curr = 2, 1 while True: yield curr curr += gap f = seq() print list(islice(f, 0, 10)) def fib(): a, b = 0, 1 while True: yield b a, b = b, a + b print fib f = fib() print f print(next(f), next(f), next(f), next(f), next(f)) def gen(): while True: value = yield print(value) g = gen() next(g) g.send("hahahha") next(g)