python迭代器实例简析

yipeiwu_com5年前Python基础

本文实例讲述了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制作填词游戏步骤详解

python制作填词游戏步骤详解

如何用PYTHON制作填词游戏 新建一个PYTHON文档。用JUPYTER NOTEBOOK打开即可。 print("Heart is " + color) print(noun...

python使用scrapy发送post请求的坑

使用requests发送post请求 先来看看使用requests来发送post请求是多少好用,发送请求 Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的...

python实现读取大文件并逐行写入另外一个文件

<pre name="code" class="python">creazy.txt文件有4G,逐行读取其内容并写入monday.txt文件里。 def crea...

python 实现矩阵上下/左右翻转,转置的示例

python中没有二维数组,用一个元素为list的list(matrix)保存矩阵,row为行数,col为列数 1. 上下翻转:只需要把每一行的list交换即可 for i in r...

python3使用pandas获取股票数据的方法

python3使用pandas获取股票数据的方法

如下所示: from pandas_datareader import data, wb from datetime import datetime import matplotli...