迭代器python与列表的区别_python学习-迭代器,列表解析和列表生成式

迭代器为类序列对象提供了一个类序列的接口。Python 的迭代无缝的支持序列对象,而且还允许程序猿迭代非序列类型,包括用户定义的对象。

迭代器是一个next()方法的对象,而不是通过索引计数。当需要下一项时,调用迭代器(Iterator)的next()方法就可以获得。条目全部取出后,会引发一个StopIterration 异常。这并不表示错误发生,只是表示迭代完成。迭代器不能向后移动,不能回到开始,也不能复制一个迭代器。

eg.

>>> myTupe = (123,'xyz',45.67)

>>> i = iter(myTupe)

>>> next(i)      在python2中方法为,i.next()

123

>>> next(i)

'xyz'

>>> next(i)

45.67

>>> next(i)

Traceback (most recent call last):

File "", line 1, in

next(i)

StopIteration

再实际应用中,需要将代码放在一个try-except 块中。

fetch = iter(seq)

while True::

try:

i  =  next(fetch)

except StopIteration:

break

do_something_to(i)

注:for 循环会自动调用迭代器的next()方法,以及见识StopIteration异常。

一般的迭代对象有序列,字典和文件。迭代

二、列表解析

列表解析用来动态的创建列表。

列表解析语法:[expr for iter_var in iterable]

语句核心是for循环,它迭代iterable 对象的所有条目。例如:

>>> [x**2 for x in range(6)]

[0, 1, 4, 9, 16, 25]

扩展语法 :[expr for iter_var in iterable if cond_expr]

>>> seq = [11,1,9,9,10,10,9,7,23,9,7,18,12,11,12]

>>> [x for x in seq if x%2

[11, 1, 9, 9, 9, 7, 23, 9, 7, 11]

>>>

迭代一个有3行5列的矩阵:

>>> [(x+1,y+1) for x in range(3) for y in range(5)]

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]

加入有一个文件test.txt,需要统计单词书

But of course now I don not get any credit for sticking with the girls all this time.

Like I said, Bryce is the most popular kid in our grade, so that leaves all the

rest of us guys scrambling for the other spots.

The best I can figure is that I am somewhere around 52nd or 53rd most popular

this year. But the good news is that I am about to move up one spot because

Charlie Davies is above me, and he is getting his braces next week

>>> with open(r'E:\test.txt','r') as f:

len([word for line in f for word in line.split()])

output:86

统计单词个数:

>>> with open(r'E:\BaiduNetdiskDownload\test.txt','r') as f:

sum([len(word) for line in f for word in line.split()])

>>>344

生成器表达式:

生成器和列表解析非常相似,基本语法相同。不过生成器不真正创建数字列表,二十返回一个生成器,每计算一个条目,把这个条目“产生”(yield)出来。所以生成器在内存上更有效。

列表解析:【expr for iter_var in iterable if cond_expr】

生成器表达式 (expt for  iter_var in iterable if cond_expt)

上例中求飞空字符的个数:

>>> with open(r'E:\BaiduNetdiskDownload\test.txt','r') as f:

sum(len(word) for line in f for word in line.split())

>>> 344

用生成式计算。它会计算每个单词的长度后传递给sum()函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值