列表推导式和生成器表达式以及字典推导式通常被视为Python中函数式编程的一部分,列表推导允许您使用包含较少代码的for循环创建列表。
列表推导式
用[] 包围
ll = [i for i in range(5)] print(ll) # [0, 1, 2, 3, 4]
ll = [i for i in range(5) if i % 2 == 0] print(ll) # [0, 2, 4]
ll = [[i, j] for i, j in enumerate(["a", "b", "c", "d"])] print(ll) # [[0, 'a'], [1, 'b'], [2, 'c'], [3, 'd']]
字典推导式
用{} 包围
dd = {i: j for i, j in enumerate(["a", "b", "c"])} print(dd) # {0: 'a', 1: 'b', 2: 'c'}
dd = {k: v for k, v in {1: 1, 2: 2, 3: 3, 4: 4}.items() if k % 2 == 0} print(dd) # {2: 2, 4: 4}
生成器表达式
生成器表达式允许在没有yield关键字的情况下即时创建生成器。
语法和概念类似于列表推导的语法和概念:用()包围
gg = (i for i in range(5)) print(gg) print(next(gg)) print(gg.__next__()) """ <generator object <genexpr> at 0x7f922e0992d0> 0 1 """
gg = (i for i in range(5)) print(gg) # <generator object <genexpr> at 0x7ffbec2992d0> for i in gg: print(i) """ <generator object <genexpr> at 0x7ffbec2992d0> 0 1 2 3 4 """