本文实例讲述了python迭代器的简单用法,分享给大家供大家参考。具体分析如下:
生成器表达式是用来生成函数调用时序列参数的一种迭代器写法
生成器对象可以遍历或转化为列表(或元组等数据结构),但不能切片(slicing)。当函数的唯一的实参是可迭代序列时,便可以去掉生成器表达式两端>的圆括号,写出更优雅的代码:
>>>> sum(i for i in xrange(10)) 45
sum声明:
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) To add floating point values with extended precision, see math.fsum().
参数要求传入可迭代序列,我们传入一个生成器对象,完美实现。
立即学习“Python免费学习笔记(深入)”;
开源计算机视觉库拥有超过2500个算法,提供详细的文档和实时计算机视觉的示例代码。它可以在Windows、Linux、Mac OS X、Android、iOS上运行,并通过JavaScript在您的浏览器中使用。语言:C++、Python、Julia、Javascript主页:https://opencv.org问答论坛:https://forum.opencv.org/文档:https://docs.opencv.org源代码:https://github.com/opencv请特别关注我们的教程!ht
20
注意区分下面代码:
上面的j为生成器类型,下面的j为list类型:
j = (i for i in range(10)) print j,type(j) print '*'*70 j = [i for i in range(10)] print j,type(j)
结果:
<generator object <genexpr> at 0x01CB1A30> <type 'generator'> ********************************************************************** [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <type 'list'>
希望本文所述对大家Python程序设计的学习有所帮助。
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号