列表推导式:用一行代码构建一个比较复杂有规律的列表
lst = []
for i in range(0,10,2): # 循环0-10里面所有数字 每次递增2个数字
lst.append(i) # 把 i 追加进 lst空列表
print (lst) # [0, 2, 4, 6, 8]
# 生成一个列表,从gpc love1 una 开始装,一直到99.
lst = ["gpc love%s una"%i for i in range (100)]
print (lst)
# #['gpc love0 una', 'gpc love1 una', 'gpc love2 una', 'gpc love3 una',.... 'gpc love99 una']
lst = [i for i in range(10) if i % 2 == 1 ] # 列表推导式
print(lst) #[1, 3, 5, 7, 9]
lst = ["王健林","王思聪","马云","马化腾"] # 字典推导式
# {0:王健林,1:王思聪,2:马云。。。}
dic = {i:lst[i] for i in range (len(lst))}
print (dic) #{0: '王健林', 1: '王思聪', 2: '马云', 3: '马化腾'}
lst = [1,1,2,3,3,4,5,5,5] # 集合推导式
s = {i for i in lst}
print (s) # {1, 2, 3, 4, 5}
g = (i for i in range(10)) #生成器
print (g) #<generator object <genexpr> at 0x000001C6A34BC2A0>
print(g.__next__()) # 0
print(g.__next__()) # 1
print ("-"*30)
for item in g: #拿空一个生成器数据
print (item) # 2 3 4 5 6 7 8 9
#100以内所有能被3整除得数得平方
lst = [i**2 for i in range(100) if i % 3 ==0]
print (lst)
# [0, 9, 36, 81, 144, 225, 324, 441, 576, 729, 900, 1089, 1296, 1521, 1764, 2025, 2304, 2601, 2916, 3249, 3600, 3969, 4356, 4761, 5184, 5625, 6084, 6561, 7056, 7569, 8100, 8649, 9216, 9801]