python 列表表达式和生成器表达式

2020-11-30 18:10:36 浏览数 (1)

参考链接: Python | 生成器表达式

列表表达式:

 >>> a=[1,2,2,3,50]

 >>> b=[i 1 for i in a]

 >>> print(b)

 [2, 3, 3, 4, 51]

 >>> b=[i 1 for i in a if i>=5]

 >>> print(b)

 [51]

 列表表达式返回一个完整的列表

 生成器表达式:

 >>> c=(i 2 for i in a )

 >>> print(c)

 <generator object <genexpr> at 0x01612030>

 >>> print(list(c))

 [3, 4, 4, 5, 52]

 生成器表达式和列表表达式的形式上并无多大差别但是执行方式上却有很大的差别,生成器表达式返回的是一个iterator 每次只返回处理单个元素,而列表表达式返回的是整个的列表,如果列表的长度很大大到占满内存的程度,那么改用生成器是有很明显的好处的

 在生成器中嵌套使用:

 >>> c=(i*2 for i in( j 1 for j in a))

 >>> print(list(c))

 [4, 6, 6, 8, 102]

 嵌套使用for字句,注意和上面的区别,这里并行写for

 >>> c=((i,j) for i in a for j in a)

 >>> print(list(c))

 [(1, 1), (1, 2), (1, 2), (1, 3), (1, 50), (2, 1), (2, 2), (2, 2), (2, 3), (2, 50), (2, 1), (2, 2), (2, 2), (2, 3), (2, 50), (3, 1), (3, 2), (3, 2), (3, 3), (3, 50), (50, 1), (50, 2), (50, 2), (50, 3), (50, 50)]

>>>   

>>> c=([i,j 1,k 2] for i in a for j in a for k in a) >>> print(list(c)) [[1, 2, 3], [1, 2, 4], [1, 2, 4], [1, 2, 5], [1, 2, 52], [1, 3, 3], [1, 3, 4], [1, 3, 4], [1, 3, 5], [1, 3, 52], [1, 3, 3], [1, 3, 4], [1, 3, 4], [1, 3, 5], [1, 3, 52], [1, 4, 3], [1, 4, 4], [1, 4, 4], [1, 4, 5], [1, 4, 52], [1, 51, 3], [1, 51, 4], [1, 51, 4], [1, 51, 5], [1, 51, 52], [2, 2, 3], [2, 2, 4], [2, 2, 4], [2, 2, 5], [2, 2, 52], [2, 3, 3], [2, 3, 4], [2, 3, 4], [2, 3, 5], [2, 3, 52], [2, 3, 3], [2, 3, 4], [2, 3, 4], [2, 3, 5], [2, 3, 52], [2, 4, 3], [2, 4, 4], [2, 4, 4], [2, 4, 5], [2, 4, 52], [2, 51, 3], [2, 51, 4], [2, 51, 4], [2, 51, 5], [2, 51, 52], [2, 2, 3], [2, 2, 4], [2, 2, 4], [2, 2, 5], [2, 2, 52], [2, 3, 3], [2, 3, 4], [2, 3, 4], [2, 3, 5], [2, 3, 52], [2, 3, 3], [2, 3, 4], [2, 3, 4], [2, 3, 5], [2, 3, 52], [2, 4, 3], [2, 4, 4], [2, 4, 4], [2, 4, 5], [2, 4, 52], [2, 51, 3], [2, 51, 4], [2, 51, 4], [2, 51, 5], [2, 51, 52], [3, 2, 3], [3, 2, 4], [3, 2, 4], [3, 2, 5], [3, 2, 52], [3, 3, 3], [3, 3, 4], [3, 3, 4], [3, 3, 5], [3, 3, 52], [3, 3, 3], [3, 3, 4], [3, 3, 4], [3, 3, 5], [3, 3, 52], [3, 4, 3], [3, 4, 4], [3, 4, 4], [3, 4, 5], [3, 4, 52], [3, 51, 3], [3, 51, 4], [3, 51, 4], [3, 51, 5], [3, 51, 52], [50, 2, 3], [50, 2, 4], [50, 2, 4], [50, 2, 5], [50, 2, 52], [50, 3, 3], [50, 3, 4], [50, 3, 4], [50, 3, 5], [50, 3, 52], [50, 3, 3], [50, 3, 4], [50, 3, 4], [50, 3, 5], [50, 3, 52], [50, 4, 3], [50, 4, 4], [50, 4, 4], [50, 4, 5], [50, 4, 52], [50, 51, 3], [50, 51, 4], [50, 51, 4], [50, 51, 5], [50, 51, 52]] >>>

0 人点赞