列表生成式 & 生成器:generator

列表生成式:

[x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

列表生成式所有数据已经生成(数据太多的话占内存

 

生成器:generator
(x * x for x in range(10)      列表生成式的  [  ]  变成()
数据没有生成,有算法(调用next函数,边执行边运算(惰性运算)目的是要最小化计算机要做的工作)

>>> g = (x * x for x in range(10))
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
File "<pyshell#169>", line 1, in <module>
next(g)
StopIteration

  

内置函数:next(iterator[, default])
通过调用 iterator 的 __next__() 方法获取下一个元素。如果迭代器耗尽,则返回给定的 default
https://docs.python.org/zh-cn/3.8/library/functions.html#next

posted @ 2023-05-12 11:58  sangern  阅读(29)  评论(0编辑  收藏  举报