本文实例讲述了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().
参数要求传入可迭代序列,我们传入一个生成器对象,完美实现。
注意区分下面代码:
上面的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)
结果:
at 0x01CB1A30> ********************************************************************** [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
希望本文所述对大家Python程序设计的学习有所帮助。
- 上一篇:python实现通过shelve修改对象实例
- 下一篇:Python中itertools模块用法详解
相关文章
相关视频
- 在Django框架中运行Python应用全攻略
- 在Python的Django框架中创建和使用模版
- python获取元素在数组中索引号的方法
- 浅谈python中截取字符函数strip,lstr...
- python迭代器实例简析
- Python 简介
- Python 环境搭建
- Python 中文编码
- Python 基础语法
- Python 变量类型
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论
立即提交
专题推荐
- 独孤九贱-php全栈开发教程
全栈 100W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
- 玉女心经-web前端开发教程
入门 50W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
- 天龙八部-实战开发教程
实战 80W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
php教程
认证0级讲师
- 最近文章
发布技术文章
- 最新文章
- 热门排行
- python之禅怎么打出来
- python怎么学
- boosting和bootstrap区别
- python库是什么意思
- python卸载后怎么也安装不上
- python安装后怎么不见了
- python怎么卸载模块
- python能做什么?是什么?
- pickle库的使用详解
- Anaconda的新手使用大全
- python爬虫是什么?为什么把python叫做爬虫?
- Python微信库:itchat的用法详解
- 关于python3学习基础知识总结
- python爬虫是什么
- 使用Python可以做什么
- python如何实现可视化热力图
推荐视频教程
视频教程分类
- php视频教程
- html视频教程
- css视频教程
- JS视频教程