栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-生成器理解到底如何工作?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-生成器理解到底如何工作?

生成器表达式就像一个列表推导,但是它没有找到你感兴趣的所有项目并将它们打包到列表中,而是等待,并逐个生成表达式中的每个项目。

>>> my_list = [1, 3, 5, 9, 2, 6]>>> filtered_list = [item for item in my_list if item > 3]>>> print(filtered_list)[5, 9, 6]>>> len(filtered_list)3>>> # compare to generator expression... >>> filtered_gen = (item for item in my_list if item > 3)>>> print(filtered_gen)  # notice it's a generator object<generator object <genexpr> at 0x7f2ad75f89e0>>>> len(filtered_gen) # So technically, it has no lengthTraceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: object of type 'generator' has no len()>>> # We extract each item out individually. We'll do it manually first.... >>> next(filtered_gen)5>>> next(filtered_gen)9>>> next(filtered_gen)6>>> next(filtered_gen) # Should be all out of items and give an errorTraceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>> # Yup, the generator is spent. No values for you!... >>> # Let's prove it gives the same results as our list comprehension... >>> filtered_gen = (item for item in my_list if item > 3)>>> gen_to_list = list(filtered_gen)>>> print(gen_to_list)[5, 9, 6]>>> filtered_list == gen_to_listTrue>>> 

由于生成器表达式一次只需要产生一项,因此可以节省大量内存。在需要一次获取一项,根据该项进行大量计算然后移至下一项的情况下,生成器表达式最有意义。如果需要多个值,则还可以使用生成器表达式,一次获取几个。如果在程序继续执行之前需要所有值,请改用列表推导。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637258.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号