# For More :http://www.codebelief.com/article/2017/02/python-advanced-programming-list-comprehensions/ # 列表生成可以非常方便地用来生成列表和迭代器 # 比如上节中map的两个例子和filter的一个例子可以用列表生成重写为 [x**2 for x in [1, 2, 3, 4]] # [1, 4, 9 16] [sum(x) for x in zip([1, 2, 3], [5, 6, 7])] # [6, 8, 10] # zip()函数可以把多个列表关联起来,这个例子中,通过zip()可以按顺序同时输出两个列表对应位置的元素对 # 有一点需要注意的是,zip()不会自动帮助判断两个列表是否长度一样,所以最终的结果会以短的列表为准 # 想要以长的列表为准的话可以考虑itertools模块中的izip_longest() [x for x in [1, 2, 3, 4, 5] if x % 2] # [1, 3, 5] # 如果要生成迭代器只需要把方括号换成括号,生成字典也非常容易: iter_odd = (x for x in [1, 2, 3, 4, 5] if x % 2) print(type(iter_odd)) # <type ‘generator‘> square_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} 至于列表生成和map/filter应该优先用哪种,这个问题很难回答,不过Python创始人Guido似乎不喜欢map/filter/reduce,他曾在表示过一些从函数式编程里拿来的特性是个错误。
原文:https://www.cnblogs.com/lcxiao/p/11361018.html