Day 21 三元表达式、生成器函数、列表解析
知识点程序:
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # __author__ = "DaChao" 4 # Date: 2017/6/16 5 6 l = [i for i in range(100) if i%2 > 0] 7 print(l) 8 9 ########################### 10 #生成器 generator!!! 模拟tail grep功能 11 ########################### 12 13 # import time 14 # def tail(filepath,encoding="utf-8"): 15 # with open(filepath,encoding=encoding) as f: 16 # f.seek(0,2) 17 # while True: 18 # line = f.readline() 19 # if line: 20 # # print("line") 21 # yield line 22 # else: 23 # time.sleep(0.5) 24 # 25 # g = tail("a.txt") 26 # for i in g: 27 # print(i) 28 29 # # tail("a.txt") 30 # def grep(lines,pattern): 31 # for line in lines: 32 # if pattern in line: 33 # print(line) 34 # # 35 36 # # for i in g: 37 # # print(g) 38 # g1 = grep(g,"error") 39 # 40 # g2 = grep(g1,"404") 41 # # 42 # for line in g2: 43 # print(line) 44 45 ########################### 46 #生成器 generator!!! yield 的重复使用 47 ########################### 48 49 # def countdown(n): 50 # print("start") 51 # while n > 0: 52 # yield n 53 # n -= 1 54 # print("end") 55 # 56 # g = countdown(5) 57 58 # print(g) 59 # print(g.__next__()) 60 # print(g.__next__()) 61 # print(g.__next__()) 62 # print(g.__next__()) 63 # print(g.__next__()) 64 # print(g.__next__()) 65 # 66 # for i in g: 67 # print(i) 68 69 70 71 ########################### 72 #生成器 带有yield 73 ########################### 74 75 # def foo(): 76 # print("1111111") 77 # yield 1 78 # print("222222222") 79 # yield 2 80 # print("33333333") 81 # yield 3 82 # 83 # g = foo() 84 # 85 # for i in g: #obj = g.__iter__() #obj,__next__ 86 # print(i) 87 88 # print(g.__next__()) 89 # print(g.__next__()) 90 # print(g.__next__()) 91 # print(g.__next__()) 92 ########################### 93 #生成器函数 94 ########################### 95 96 # def lay_eggs(num): 97 # ''' 98 # 存鸡蛋! 99 # :param num: 100 # :return: 101 # ''' 102 # egg_list = [] 103 # for egg in range(num): 104 # egg_list.append("egg%s" %egg) 105 # return egg_list 106 107 # yikuangdan = lay_eggs(10) 108 # for i in yikuangdan: #下蛋 109 # print(i) 110 111 # def lay_eggs1(num): 112 # for egg in range(num): 113 # res = "egg%s" %egg 114 # yield res 115 # print("Egg +") 116 # 117 # laomuji = lay_eggs1(10) 118 # print(laomuji) 119 # print(laomuji.__next__()) 120 # print(laomuji.__next__()) 121 # print(laomuji.__next__()) 122 # print(laomuji.__next__()) 123 # egg_l = list(laomuji) 124 # print(egg_l) 125 126 127 ########################## 128 #迭代器 129 ########################### 130 131 # d = {"a":1,"b":2,"c":3} 132 # 133 # obj = d.__iter__() 134 # 135 # while True: 136 # try: 137 # i = obj.__next__() 138 # print(i) 139 # except StopIteration: 140 # break