python-生成器进阶~生成器表达式
列表推导式
y = [1,2,3,4,5,6,7,8] x = [1,4,9,16,25,36,49,64] # 方法一: x = [] for i in y: x .append(i*i) print(x) # 方法二 x = [i*i for i in y] print(x)
li= [i/2 for i in range(100)] print(li) x = [i*i for i in y] print(x)
生成器表达式
例题
y = [1,2,3,4,5,6,7,8] g = (i*i for i in y) #列表可以使用推导式,生成器也可以使用表达式 print(g) print(list(g)) #使用list把生成器强转成为列表 for i in g: print(i) laomuji=('鸡蛋%s' %i for i in range(10)) print(laomuji) print(next(laomuji)) print(laomuji.__next__()) g = (i*i for i in range(30) if i % 3 is 0) for i in g: print(i) print([i for i in range(30) if i%3 == 0]) print([i*i for i in range(30) if i%3 == 0])