Python 列表解析器&生成器表达式

列表解析器

It can be used to construst lists in a very natural, easy way, like a mathematician is used to do.

1
[expr for iter_var in iterable if cond_expr]

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

1
2
3
4
>>> [x*x for x in range (100) if x*x < 50 ]
[0, 1, 4, 9, 16, 25, 36, 49]
>>> type([x*x for x in range (100) if x*x < 50 ])
<type 'list'>

生成器表达式

A generator expression yields a new generator object. It consists of a single expression followed by at least one for clause and zero or more for or if clauses. The iterating values of the new generator are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to yield a value that is reached the innermost block for each iteration.

1
(expr for iter_var in iterable if cond_expr)

不创建列表,只是返回一个生成器。这个生成器在每次计算出一个条目后,才把这个条目产生出来。所以在处理大量数据时更有优势。

1
2
3
4
>>> type (r for r in range(10))
<type 'generator'>
>>> dict ((r,0) for r in range(10))
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
您的支持将鼓励我继续创作!