假设一个列表的存有 数量很大的元素,但是在每一次运行时,通常只调用前面几个元素,这时为了优化,可以采用生成器.
isList = [x * x for x in range(10)]
print(isList) # 结果[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
isGenerator = (x * x for x in range(10))
print(isGenerator) # 这里显示的结果是生成器的地址<generator object <genexpr> at 0x0000028E39D79938>
print("result : %d " % next(isGenerator)) # result : 0
print("result : %d " % next(isGenerator)) # result : 1
print("result : %d " % next(isGenerator)) # result : 4
for i in isGenerator:
print(i) # 依次是 9, 16, 25, 36, 49, 64, 81
for it in isGenerator:
print("this time : %d" % it) # 结果为空,这时如果继续调用next(isGenerator),会报StopIteration(因为越界).