python迭代器实例简析

作者:shichen2014 时间:2023-07-26 07:40:29 

本文实例讲述了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)

结果:


<generator object <genexpr> at 0x01CB1A30> <type 'generator'>
**********************************************************************
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <type 'list'>

希望本文所述对大家Python程序设计的学习有所帮助。

标签:python,迭代器
0
投稿

猜你喜欢

  • pytorch中fuse_modules源码解读

    2023-09-15 20:58:01
  • Django实现jquery select2带搜索的下拉框

    2022-04-20 18:50:58
  • 童年回忆录之python版4399吃豆豆小游戏

    2021-04-30 18:52:44
  • python数据清洗系列之字符串处理详解

    2023-08-02 04:00:07
  • Mysql数据库的安全性问题释疑

    2009-02-26 16:20:00
  • 在Python的Flask框架中使用模版的入门教程

    2021-09-14 04:57:59
  • 使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件及出现问题解决方法

    2021-09-17 08:53:15
  • php之二维数组排序问题

    2023-07-15 06:44:42
  • oracle 合并查询 事务 sql函数小知识学习

    2023-07-13 15:07:28
  • 前端页面文件拖拽上传模块js代码示例

    2023-09-20 02:15:30
  • js判断手机和pc端选择不同执行事件的方法

    2024-04-29 13:45:46
  • Jupyter notebook中5个有趣的魔法命令分享

    2021-11-28 23:26:30
  • Python Django 通用视图和错误视图的使用代码

    2023-02-20 04:17:47
  • 去掉前面的0的sql语句(前导零,零前缀)

    2011-09-30 11:28:19
  • JS获取对象代码总结

    2011-03-07 16:14:00
  • 网络基础-数据包

    2022-11-24 21:48:10
  • python中bisect模块用法实例

    2023-03-13 16:23:42
  • XHTML1.0与HTML兼容指引16条[译]

    2009-06-10 14:45:00
  • python opencv实现目标区域裁剪功能

    2022-07-15 19:17:56
  • 浅谈Go切片的值修改是否会覆盖数组的值 

    2024-04-26 17:18:19
  • asp之家 网络编程 m.aspxhome.com