列表推导式是一种轻量级的循环创建列表,列表生成式是一种简化代码的优美方式
以下使用代码,展示一下列表推导式的使用:
1.生成一个0-9的列表
s1 = [x for x in range(10)]
2.根据已有的列表快速创建一个新列表
s2 = [1,2,3,4,5,6,7,8,9] s3 = [x*3 for x in s2]
3.根据存在列表创建嵌套列表
s4 = [1,2,3] s5 = [[x,x*2] for x in s4]
4.使用if子句作为过滤器
s5 = [1,2,3,4,5,6,7,8,9] s6 = [x for x in s5 if x%2==0]
5.根据两个列表创建一个列表
s7 = [1,2,3,4,5] s8 = [2,3,4,5] s9 = [x*y for x in s7 for y in s8]
6.两个for循环
1 s10 = [1,2,3,4,5,6] 2 3 s11 = [0,9,8,7,6] 4 5 s12 = [2,3,4,7,8,9] 6 7 s13 = [(x,y,z) for x in s10 for y in s11 for z in s12]
7.三个for循环
1 s14 = [(x,y,z) for x in range(5) if x%2==0 for y in range(5) for z in range(5)if y%2!=0]
8.根据列表推导式将一个3*4的列表,快速修改为一个4*3的问题
1 list = [[1,2,3,4], 2 3 [5,6,7,8], 4 5 [9,10,11,12], 6 ] 7 8 list2 = [[row[i] for row in list] for i in range(4)]
以上是几种常见的列表推导式,比for循环创建列表更简洁更快速!