python 中列表推导式,主要完成快速赋值,快速生成列表、元组、字典等应用场景。是一个非常好用的工具。在一些排序过程还可以做为参数传入函数。
1.先来一个尝试一下
alist = [x for x in range(1,10)] print(alist) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 深入接触一下
import time alist = [x for x in range(1,10)] print(alist) blist = [x for x in range(1,10)] startTime = time.time() alllist = [] for x in range(1,11): alllist.append(x) print(alist) al = [ x+x for x in alist] print(al) al1 = [x*x for x in alist] print(al1) endTime = time.time() print("结束:",(endTime - startTime),"秒") #过滤被2除 al2 = [i for i in alist if i % 2 == 0] print(al2)