列表推导式 [结果 for循环 if]
字典推导式 {结果(k:v) for循环 if}
集合推导式 {结果(k) for循环 if}
# 生成列表: python1->python18 # lst = [] # for i in range(1, 19): # lst.append("python%s期" % i) # # print(lst) # 列表推导式 [结果 for循环 if条件] # lst = ["python%s期" % i for i in range(1, 19)] # print(lst) # 生成列表.类表中装的数据是 1-100之间所有的偶数的平方 # lst = [i**2 for i in range(1, 101) if i%2 == 0] # print(lst) # 筛选出列表中姓张的同学, lst = ["张无忌", "吴奇隆", "张诗诗", "范冰冰", "张翠山"] # lst = ["张无忌", "吴奇隆", "张诗诗", "范冰冰", "张翠山"] # lst2 = [name for name in lst if name.startswith("张")] # print(lst2) # # 寻找名字中带有两个e的人的名字 # names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven','Joe'], # ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] # # lst = [name for el in names for name in el if name.count("e") == 2] # print(lst) # 字典推导式 # 语法: { 结果(key:value) for循环 if条件} # lst = [11,22,33] # {0:11, 1:22, 2:33} # # dic = {i:lst[i] for i in range(len(lst))} # print(dic) # 练习: {"主食": "炒面", "副食": "小拌菜", "汤":"疙瘩汤"} # 把字典的key和value互换, 生成新字典 # dic = {"主食": "炒面", "副食": "小拌菜", "汤":"疙瘩汤"} # d = { v:k for k, v in dic.items()} # print(d) # 集合推导式 {k for循环 if 条件} # 没有元组推导式 # g = (i for i in range(10)) # 生成器表达式 # # print(g) # <generator object <genexpr> at 0x0000000009E573B8> # # print(g.__next__()) # 0 # print(g.__next__()) # 1 # print(g.__next__()) # 2 # print(g.__next__()) # 3 # print(g.__next__()) # 4 # print(g.__next__()) # 5 # print(g.__next__()) # 6 # print(g.__next__()) # 7 # print(g.__next__()) # 8 # print(g.__next__()) # 9 # # print(g.__next__()) # ??? StopIteration # # # g = (i for i in range(10)) # 生成器表达式 # 生成器函数 # def func(): # print(111) # yield 222 # # # 惰性机制, 只能向前 # g = func() # 创建生成器 # g1 = (i for i in g) # 生成器表达式 # g2 = (i for i in g1) # 生成器表达式 # # # # print(list(g1)) # print(list(g)) # for -> __next__() # print(list(g2))