生成器Generator def countdown(num): print('Starting') while num > 0: yield num num -= 1 # this will not print 'Starting' cd = countdown(3) # this will print 'Starting' and the first value print(next(cd)) # will print the next values print(next(cd)) print(next(cd)) # this will raise a StopIteration print(next(cd)) 迭代器使用方式 # you can iterate over a generator object with a for in loop cd = countdown(3) for x in cd: print(x) # you can use it for functions that take iterables as input cd = countdown(3) sum_cd = sum(cd) print(sum_cd) cd = countdown(3) sorted_cd = sorted(cd) print(sorted_cd) 生成器表达式 # generator expression mygenerator = (i for i in range(1000) if i % 2 == 0) print(sys.getsizeof(mygenerator), "bytes") # list comprehension mylist...