python:迭代器和列表解析

来源:互联网 发布:软件开发学徒骗局 编辑:程序博客网 时间:2024/05/16 06:46

创建迭代器:

对一个对象调用 iter() 就可以得到它的迭代器. 它的语法如下:

iter(obj)
iter(func, sentinel )

如果你传递一个参数给 iter() , 它会检查你传递的是不是一个序列, 如果是, 那么很简单:根据索引从 0 一直迭代到序列结束.

另一个创建迭代器的方法是使用类,一个实现了 __iter__() 和 next() 方法的类可以作为迭代器使用.

如 果 是 传 递 两 个 参 数 给 iter() , 它 会 重 复 地 调 用 func , 直 到 迭 代 器 的 下 个 值 等 于sentinel .


列表解析:

1、解析语法:

[expr for iter_var in iterable]

这个语句的核心是 for 循环, 它迭代 iterable 对象的所有条目. 前边的 expr 应用于序列的每个成员, 最后的结果值是该表达式产生的列表. 迭代变量并不需要是表达式的一部分.

>>> [x ** 2 for x in range(6)]  #它有一个计算序列成员的平方 [0, 1, 4, 9, 16, 25]
2、列表解析还提供了一个扩展版本的语法:
[expr for iter_var in iterable if cond_expr]

这个语法在迭代时会过滤/捕获满足条件表达式 cond_expr 的序列成员.

>>> seq = [11, 10, 9, 9, 10, 10, 9, 8, 23, 9, 7, 18, 12, 11, 12] 
>>> [x for x in seq if x % 2] #它用于判断一个数值对象是奇数还是偶数(奇数返回 1 , 偶数返回 0 ) [11, 9, 9, 9, 23, 9, 7, 11]
===磁盘文件样例===
假设我们有如下这样一个数据文件 hhga.txt , 需要计算出所有非空白字符的数目:
And the Lord spake, saying, "First shalt thou take
out the Holy Pin. Then shalt thou count to three,

no more, no less. Three shall be the number thou shalt
count, and the number of the counting shall be three.
Four shalt thou not count, nei- ther count thou two,
excepting that thou then proceed to three. Five is
right out. Once the number three, being the third
number, be reached, then lobbest thou thy Holy Hand
Grenade of Antioch towards thy foe, who, being
naughty in My sight, shall snuff it."

我们已经知道可以通过 for line in data 迭代文件内容, 不过, 除了这个, 我们还可以把每行分割( split )为单词, 然后我们可以像这样计算单词个数:

>>> f = open('hhga.txt', 'r')>>> len([word for line in f for word in line.split()])91

生成器表达式:
(expr for iter_var in iterable) 或 (expr for iter_var in iterable if cond_expr) 

生成器表达式就好像是懒惰的列表解析(这反而成了它主要的优势). 它还可以用来处理其他列表或生成器

>>> L= (i + 1 for i in range(10) if i % 2)>>> L<generator object <genexpr> at 0xb749a52c>>>> L1=[]>>> for i in L:... L1.append(i)...>>> L1[2, 4, 6, 8, 10] 
生成器表达式并不真正创建数字列表, 而是返回一个生成器,这个生成器在每次计算出一个条目后,把这个条目“产生”(yield)出来。 生成器表达式使用了“惰性计算”(lazy evaluation,也有翻译为“延迟求值”,我以为这种按需调用call by need的方式翻译为惰性更好一些),只有在检索时才被赋值( evaluated),所以在列表比较长的情况下使用内存上更有效。A generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them.





0 0
原创粉丝点击