计算
ls1 = [1, 2, 3, 4]
ls2 = [i * 2 for i in ls1]
print(ls2)
既然是列表推导式,显然这是针对列表的;
ls2的意思是从ls1里面依次取出元素;
对每次取出的元素i进行乘以2的运算;
新值作为一个元素,依次添加到ls2中;
判断
ls1 = [1, 2, 3, 4]
ls2 = [i for i in ls1 if i % 2 == 0]
print(ls2)
它的语法结构就是把判断词if加到后面;
30以内所有数的平方
ls = [i ** 2 for i in range(30) if i % 3 == 0]
print(ls)
网友评论