语法:
[ expr for iter_var in iterable ]
说明:
for循环迭代iterable对象的所有条目。前面的expr应用于序列的每个成员,最后的结果值是该表达式产生的列表。
示例:
>>> [ x**2 for x in range(6) ] [0, 1, 4, 9, 16, 25] >>> [(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)] >>>
还可以结合if语句进行扩展:
[ expr for iter_var in iterable if cond_expr ]
>>> seq = [11,10,9,9,10,10,9,8,23,9,7,18,12,11,23] >>> [ x for x in seq if x%2 ] [11, 9, 9, 9, 23, 9, 7, 11, 23] >>>